mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-03 11:18:30 -06:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
384d41d6ff | ||
|
|
6681531546 | ||
|
|
97fed2970c | ||
|
|
44fa197bcc | ||
|
|
36e8c31f0d | ||
|
|
17fb7a3c43 | ||
|
|
5ab5e6f343 | ||
|
|
5a7182240e | ||
|
|
e7d05e1b42 | ||
|
|
d55ac7ba7a | ||
|
|
0623c42d10 | ||
|
|
738230f7ea |
@@ -30,6 +30,7 @@ Generated-in-code assets are original and have no file to list:
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
|
||||
| `vendor/wgpu-hal/` | wgpu developers; Metal language probe by CADCraft contributors | [wgpu-hal 30.0.1](https://crates.io/crates/wgpu-hal/30.0.1) ([gfx-rs/wgpu 40f4a34e](https://github.com/gfx-rs/wgpu/tree/40f4a34ebaf56f9a046231f54125ad046239d3f3/wgpu-hal)), same patch as [storytold/craft-anything vendor/wgpu-hal](https://github.com/storytold/craft-anything/tree/6c7d1f07f9f33643714bd203e1e004f04481f28e/vendor/wgpu-hal) | MIT OR Apache-2.0 | Graphics dependency, patched in `src/metal/adapter.rs` only (#1631); see `vendor/wgpu-hal/CADCRAFT.md`. |
|
||||
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
|
||||
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.6](https://crates.io/crates/acadrust/0.6.6), [hakanaktt/acadrust](https://github.com/hakanaktt/acadrust), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
|
||||
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.6 third-party notices](https://github.com/hakanaktt/acadrust/blob/v0.6.6/THIRD_PARTY_NOTICES.md), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
|
||||
|
||||
Generated
+2
-2
@@ -781,6 +781,8 @@ dependencies = [
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"x11-dl",
|
||||
"xkbcommon-dl",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
@@ -7275,8 +7277,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "wgpu-hal"
|
||||
version = "30.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"arrayvec",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
# Patched third-party crates under [patch.crates-io], not ours to lint or test.
|
||||
exclude = ["vendor/wgpu-hal"]
|
||||
# default-members
|
||||
|
||||
[workspace.package]
|
||||
@@ -130,6 +132,10 @@ hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
|
||||
# wgpu-hal that picks a Metal language version the system compiler accepts, not the OS's alone
|
||||
# (#1631; upstream gfx-rs/wgpu#10687). See vendor/wgpu-hal/CADCRAFT.md for when to remove it.
|
||||
wgpu-hal = { path = "vendor/wgpu-hal" }
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
|
||||
@@ -396,6 +396,20 @@ RISC-V (riscv64) packages are `cadcraft-<ver>-linux-riscv64.deb`,
|
||||
`cadcraft-<ver>-linux-riscv64.rpm`, and `cadcraft-<ver>-linux-riscv64.tar.gz`. They are
|
||||
cross-compiled and need glibc 2.39 or newer (Ubuntu 24.04+, Debian 13+).
|
||||
|
||||
**Wayland:** on a Wayland desktop the app uses the native Wayland backend, which is sharp at
|
||||
fractional scales, works with input methods and accepts files dropped from the file manager. If
|
||||
the native backend misbehaves on your desktop, run the app through XWayland instead with
|
||||
`CADCRAFT_X11=1` (this needs the X11 libraries: libX11, libX11-xcb, libXcursor, libXi and
|
||||
libxkbcommon-x11):
|
||||
|
||||
```sh
|
||||
CADCRAFT_X11=1 cadcraft
|
||||
```
|
||||
|
||||
GNOME on Wayland draws no window frames, so there CADCraft's title bar carries the window
|
||||
buttons, in GNOME's order. **Options ▸ Display ▸ Use system title bar** shows a basic frame
|
||||
instead. `CADCRAFT_TITLEBAR=app` or `CADCRAFT_TITLEBAR=system` overrides the detection.
|
||||
|
||||
### FreeBSD
|
||||
|
||||
| Build | File |
|
||||
|
||||
@@ -40,6 +40,12 @@ winresource = "0.1"
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
# Checks that the X11 libraries are installed before choosing XWayland (see main.rs). Already in
|
||||
# the build through winit, at this version.
|
||||
x11-dl = "2.21"
|
||||
# Checks for libxkbcommon-x11 too, which winit's X11 backend needs for the keyboard and panics
|
||||
# without. Already in the build through winit, at this version and with this feature.
|
||||
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
|
||||
# View ▸ Theme ▸ System: the desktop's light/dark choice from the XDG desktop portal
|
||||
# (desktop_theme.rs). Already in Cargo.lock through accesskit; pinned to that version so nothing
|
||||
# is built twice.
|
||||
|
||||
@@ -12,7 +12,7 @@ const CONFIG_DIR: &str = "CADCRAFT_CONFIG_DIR";
|
||||
const LOCALE: &str = "CADCRAFT_LOCALE";
|
||||
const VSYNC: &str = "CADCRAFT_VSYNC";
|
||||
const STENCIL: &str = "CADCRAFT_STENCIL";
|
||||
const WAYLAND: &str = "CADCRAFT_WAYLAND";
|
||||
const X11: &str = "CADCRAFT_X11";
|
||||
const NO_NATIVE_MENU: &str = "CADCRAFT_NO_NATIVE_MENU";
|
||||
const SYSTEM_CURSOR: &str = "CADCRAFT_SYSTEM_CURSOR";
|
||||
const FONTALT: &str = "CADCRAFT_FONTALT";
|
||||
@@ -27,7 +27,7 @@ pub(crate) const VARS: &[(&str, &str)] = &[
|
||||
STENCIL,
|
||||
"0 opens the window without a stencil buffer, 1 keeps it on every attempt; unset, a start that can't draw with it drops it (clipped layout viewports then draw unclipped)",
|
||||
),
|
||||
(WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"),
|
||||
(X11, "1 runs through XWayland instead of the native Wayland backend, as a fallback, when the X11 libraries load; 0 or unset is off"),
|
||||
(NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"),
|
||||
(SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"),
|
||||
(FONTALT, "the font that replaces a missing one"),
|
||||
@@ -54,9 +54,9 @@ pub(crate) struct Env {
|
||||
/// `renderer`). Some old drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a
|
||||
/// stencil pass and then present a black window.
|
||||
pub(crate) stencil: Switch,
|
||||
/// Keep the native Wayland backend instead of XWayland.
|
||||
/// Run through XWayland instead of the native Wayland backend.
|
||||
#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]
|
||||
pub(crate) wayland: Switch,
|
||||
pub(crate) x11: Switch,
|
||||
/// macOS: keep the menus inside the window.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
pub(crate) no_native_menu: Switch,
|
||||
@@ -121,7 +121,7 @@ impl Env {
|
||||
locale: text(LOCALE),
|
||||
vsync: switch(VSYNC),
|
||||
stencil: switch(STENCIL),
|
||||
wayland: switch(WAYLAND),
|
||||
x11: switch(X11),
|
||||
no_native_menu: switch(NO_NATIVE_MENU),
|
||||
system_cursor: switch(SYSTEM_CURSOR),
|
||||
font_alt: text(FONTALT),
|
||||
@@ -223,7 +223,7 @@ mod tests {
|
||||
(LOCALE, "cs-CZ"),
|
||||
(VSYNC, " On "),
|
||||
(STENCIL, "No"),
|
||||
(WAYLAND, "0"),
|
||||
(X11, "0"),
|
||||
(NO_NATIVE_MENU, "yes"),
|
||||
(SYSTEM_CURSOR, "maybe"),
|
||||
(FONTALT, "Noto Sans"),
|
||||
@@ -238,7 +238,7 @@ mod tests {
|
||||
locale: Some("cs-CZ".into()),
|
||||
vsync: Switch::On,
|
||||
stencil: Switch::Off,
|
||||
wayland: Switch::Off,
|
||||
x11: Switch::Off,
|
||||
no_native_menu: Switch::On,
|
||||
system_cursor: Switch::Default,
|
||||
font_alt: Some("Noto Sans".into()),
|
||||
@@ -249,7 +249,7 @@ mod tests {
|
||||
let read = Env::from_vars(env(&blank));
|
||||
assert_eq!(read.config_dir, None, "an empty variable means no directory, not the working directory");
|
||||
assert_eq!((read.locale, read.font_alt, read.font_fallback), (None, None, None));
|
||||
assert_eq!([read.vsync, read.stencil, read.wayland, read.no_native_menu, read.system_cursor], [Switch::Default; 5]);
|
||||
assert_eq!([read.vsync, read.stencil, read.x11, read.no_native_menu, read.system_cursor], [Switch::Default; 5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -498,6 +498,38 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
Some(launch.passthrough_args)
|
||||
}
|
||||
|
||||
/// Whether the libraries winit's X11 backend opens at startup are installed (libX11, libXcursor,
|
||||
/// libX11-xcb and libXi; libX11-xcb brings in libxcb; and libxkbcommon-x11, for the keyboard).
|
||||
/// The deb and rpm only recommend them, and a forced X11 backend without them fails to start
|
||||
/// (winit panics when libxkbcommon-x11 is missing).
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn x11_libraries_load() -> bool {
|
||||
use x11_dl::{xcursor::Xcursor, xinput2::XInput2, xlib::Xlib, xlib_xcb::Xlib_xcb};
|
||||
let missing = [Xlib::open().err(), Xcursor::open().err(), Xlib_xcb::open().err(), XInput2::open().err()];
|
||||
let mut missing: Vec<String> = missing.into_iter().flatten().map(|e| e.to_string()).collect();
|
||||
if xkbcommon_dl::x11::xkbcommon_x11_option().is_none() {
|
||||
missing.push("libxkbcommon-x11.so.0 could not be loaded".into());
|
||||
}
|
||||
if !missing.is_empty() {
|
||||
log::warn!("CADCRAFT_X11: X11 libraries missing, using the native Wayland backend: {}", missing.join("; "));
|
||||
}
|
||||
missing.is_empty()
|
||||
}
|
||||
|
||||
/// Whether to force winit's X11 backend (XWayland on a Wayland desktop): an X display is there,
|
||||
/// `CADCRAFT_X11` is on, and the X11 libraries load. The libraries are probed last, only when X11
|
||||
/// would otherwise be chosen.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn use_x11(display: bool, setting: Switch, x11_libraries_load: impl FnOnce() -> bool) -> bool {
|
||||
display && setting == Switch::On && x11_libraries_load()
|
||||
}
|
||||
|
||||
/// Whether a display variable names something: set and not empty, as winit reads them.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn set(v: Option<&std::ffi::OsStr>) -> bool {
|
||||
v.is_some_and(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
|
||||
fn main() -> eframe::Result {
|
||||
// A copy of this program started to read or write a DWG file does only that. It is started
|
||||
@@ -589,9 +621,21 @@ fn main() -> eframe::Result {
|
||||
cadcraft_engine::fonts::ttf::set_fallback_fonts(list);
|
||||
}
|
||||
let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos"))));
|
||||
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
|
||||
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
|
||||
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
|
||||
// winit runs natively on a Wayland desktop: sharp at fractional scales, with working input
|
||||
// methods, and file drops from the file manager through storytold/winit's W15 patch.
|
||||
// CADCRAFT_X11=1 runs through XWayland instead, as a fallback where the native backend
|
||||
// misbehaves; 0, off or unset leaves it off. The X11 libraries are only recommended by the
|
||||
// packages, so without them the setting is ignored rather than failing.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let forced_x11 = use_x11(set(std::env::var_os("DISPLAY").as_deref()), vars.x11, x11_libraries_load);
|
||||
#[cfg(not(all(unix, not(target_os = "macos"))))]
|
||||
let forced_x11 = false;
|
||||
// Read before the window opens: Use system title bar decides the window's frame.
|
||||
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
|
||||
// Where the desktop leaves the window frame to the app (GNOME on Wayland), the framework's title
|
||||
// bar carries the window buttons, unless Options ▸ Display ▸ Use system title bar is on.
|
||||
let title_bar = cadcraft_ui_egui::title_bar::decide(forced_x11, restored.as_ref().is_some_and(|ui| ui.system_title_bar));
|
||||
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11).or_else(|| title_bar.as_ref().map(|t| t.decision().clone()));
|
||||
let persistence_path = vars
|
||||
.portable_storage_file
|
||||
.clone()
|
||||
@@ -620,9 +664,6 @@ fn main() -> eframe::Result {
|
||||
d
|
||||
});
|
||||
}
|
||||
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
|
||||
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
|
||||
// keeps the native Wayland backend.
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if forced_x11 {
|
||||
options.event_loop_builder = Some(Box::new(|b| {
|
||||
@@ -666,7 +707,6 @@ fn main() -> eframe::Result {
|
||||
{
|
||||
app.services.start_pick = Some(start_pick(cc.egui_ctx.clone()));
|
||||
}
|
||||
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
|
||||
if let Some(ui) = restored {
|
||||
app.ui = ui;
|
||||
}
|
||||
@@ -716,6 +756,9 @@ fn main() -> eframe::Result {
|
||||
app.session.set_lisp_support_dir(Some(support));
|
||||
}
|
||||
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
|
||||
if let Some(title_bar) = title_bar {
|
||||
app.set_title_bar(title_bar);
|
||||
}
|
||||
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
|
||||
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
|
||||
}
|
||||
@@ -781,6 +824,37 @@ mod tests {
|
||||
use super::{filters_for_save, follow_desktop, nightly_version_line, saved_window, version_string, window_options, without_tiny_window};
|
||||
use crate::renderer::STENCIL_BITS;
|
||||
|
||||
/// A Wayland desktop without the X11 libraries (libxkbcommon-x11 removed, or a package
|
||||
/// installed without its recommendations) crashed at startup: X11 was forced through XWayland
|
||||
/// and winit panicked loading them. Native Wayland is now the default, `CADCRAFT_X11=1` asks
|
||||
/// for X11 only when the libraries load, and probing them never panics, whichever of them
|
||||
/// this machine has.
|
||||
#[test]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn x11_only_when_asked_for_and_the_libraries_load() {
|
||||
use super::{use_x11, x11_libraries_load};
|
||||
use cadcraft_ui_egui::switch::Switch;
|
||||
let unprobed = || -> bool { panic!("the libraries are probed only when X11 would be chosen") };
|
||||
assert!(!use_x11(true, Switch::Default, unprobed), "native Wayland by default");
|
||||
assert!(!use_x11(true, Switch::Off, unprobed), "CADCRAFT_X11=0 leaves it off");
|
||||
assert!(!use_x11(false, Switch::On, unprobed), "no X display");
|
||||
assert!(use_x11(true, Switch::On, || true));
|
||||
assert!(!use_x11(true, Switch::On, || false), "missing X11 libraries: native Wayland, no crash");
|
||||
let loaded = x11_libraries_load();
|
||||
assert_eq!(use_x11(true, Switch::On, || loaded), loaded);
|
||||
}
|
||||
|
||||
/// An empty `DISPLAY` names no X server, so `CADCRAFT_X11=1` can't force X11 with it.
|
||||
#[test]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
fn an_empty_display_is_no_display() {
|
||||
use super::set;
|
||||
use std::ffi::OsStr;
|
||||
assert!(set(Some(OsStr::new(":0"))));
|
||||
assert!(!set(Some(OsStr::new(""))));
|
||||
assert!(!set(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
|
||||
let first = |name: &str| filters_for_save(name)[0].1;
|
||||
|
||||
@@ -50,6 +50,7 @@ fn snapshot(ui: &UiState) -> Result<Value, String> {
|
||||
"propertiesAll": ui.properties_all,
|
||||
"inWindowMenu": ui.in_window_menu,
|
||||
"historyLines": ui.history_lines,
|
||||
"systemTitleBar": ui.system_title_bar,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -219,6 +220,7 @@ mod tests {
|
||||
ui.toolset_tab = "Modeling".into();
|
||||
ui.collapsed_groups = vec!["Solid".into()];
|
||||
ui.history_lines = 5;
|
||||
ui.system_title_bar = true;
|
||||
ui.dialog = Some("layers".into());
|
||||
ui.start_tab = true;
|
||||
first.save_if_changed(&ui, Instant::now()).unwrap();
|
||||
@@ -226,6 +228,7 @@ mod tests {
|
||||
let value: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert!(value["workspace"].get("dialog").is_none());
|
||||
assert!(value["workspace"].get("startTab").is_none());
|
||||
assert_eq!(value["workspace"]["systemTitleBar"], true, "read before the window opens");
|
||||
let (_, restored, error) = Workspace::at(Some(path.clone()));
|
||||
assert!(error.is_none());
|
||||
let restored = restored.unwrap();
|
||||
@@ -340,6 +343,7 @@ mod tests {
|
||||
assert_eq!(restored.toolset_tab, "Modeling");
|
||||
assert_eq!(restored.collapsed_groups, ["Draw"]);
|
||||
assert_eq!(restored.history_lines, 7);
|
||||
assert!(!restored.system_title_bar, "older files keep the app's window buttons");
|
||||
assert_eq!(serde_json::to_value(restored.docking).unwrap(), serde_json::to_value(UiState::default().docking).unwrap());
|
||||
}
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
|
||||
+131
-6
@@ -7,9 +7,15 @@
|
||||
//! it draws at paper size × that view's annotation scale, and only in views whose scale it
|
||||
//! supports unless `ANNOALLVISIBLE` is 1. Model space is seen at `CANNOSCALE`, a layout viewport
|
||||
//! at its viewport scale, and paper space itself at 1:1.
|
||||
//!
|
||||
//! An object supporting several scales can sit somewhere else at one of them ([`AnnoMove`]): its
|
||||
//! grips move it at the current scale only, and ANNORESET puts every scale back where the current
|
||||
//! one is. What moves is the object's position ([`shift_position`]).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use cadcraft_geom::{Mat3, Vec2};
|
||||
|
||||
use crate::{Common, Drawing, Entity, EntityKind};
|
||||
|
||||
/// A named annotation scale: `paper_units` on paper show `drawing_units` of the drawing.
|
||||
@@ -87,6 +93,13 @@ pub fn imperial_scales() -> Vec<AnnoScale> {
|
||||
v
|
||||
}
|
||||
|
||||
/// How far an annotative object sits from its shared position at the scale named `scale`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnnoMove {
|
||||
pub scale: String,
|
||||
pub by: Vec2,
|
||||
}
|
||||
|
||||
/// Kinds that can be annotative.
|
||||
pub fn can_be_annotative(k: &EntityKind) -> bool {
|
||||
matches!(
|
||||
@@ -105,6 +118,7 @@ pub fn is_annotative(e: &Entity) -> bool {
|
||||
pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
|
||||
if !on {
|
||||
e.common.anno_scales.clear();
|
||||
e.common.anno_moves.clear();
|
||||
} else if can_be_annotative(&e.kind) && e.common.anno_scales.is_empty() {
|
||||
e.common.anno_scales.push(current.clone());
|
||||
}
|
||||
@@ -115,8 +129,9 @@ pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
|
||||
pub enum AnnoDraw {
|
||||
/// Not annotative: as stored.
|
||||
Plain,
|
||||
/// Annotative, at this factor (drawing units per paper unit).
|
||||
Scaled(f64),
|
||||
/// Annotative, at `factor` (drawing units per paper unit), its position moved `by` at that
|
||||
/// scale.
|
||||
Scaled { factor: f64, by: Vec2 },
|
||||
/// Annotative and not supporting the view's scale, with `ANNOALLVISIBLE` 0.
|
||||
Hidden,
|
||||
}
|
||||
@@ -130,6 +145,76 @@ impl Common {
|
||||
pub fn supports_scale(&self, name: &str) -> bool {
|
||||
self.anno_scales.iter().any(|s| s.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
/// How far the object sits from its shared position at the scale named `name`.
|
||||
pub fn moved_at(&self, name: &str) -> Vec2 {
|
||||
self.anno_moves.iter().find(|m| m.scale.eq_ignore_ascii_case(name)).map(|m| m.by).filter(|v| v.is_finite()).unwrap_or(Vec2::ZERO)
|
||||
}
|
||||
/// How far the object sits from its shared position at its scale with the ratio `factor`.
|
||||
pub fn moved_at_factor(&self, factor: f64) -> Vec2 {
|
||||
self.anno_scales.iter().find(|s| s.has_factor(factor)).map_or(Vec2::ZERO, |s| self.moved_at(&s.name))
|
||||
}
|
||||
/// Move the object `by` at the scale named `name` only (an offset that comes to nothing is
|
||||
/// dropped).
|
||||
pub fn move_at(&mut self, name: &str, by: Vec2) {
|
||||
if !by.is_finite() {
|
||||
return;
|
||||
}
|
||||
let to = self.moved_at(name) + by;
|
||||
self.anno_moves.retain(|m| !m.scale.eq_ignore_ascii_case(name));
|
||||
if to.len() > 1e-12 * (1.0 + by.len()) && self.anno_moves.len() < MAX_SCALES {
|
||||
self.anno_moves.push(AnnoMove { scale: name.to_string(), by: to });
|
||||
}
|
||||
}
|
||||
/// Turn the offsets with `m`'s linear part (MOVE leaves them, ROTATE turns them, SCALE sizes
|
||||
/// them, MIRROR mirrors them), as the shared position goes through `m`.
|
||||
pub fn transform_moves(&mut self, m: &Mat3) {
|
||||
for mv in &mut self.anno_moves {
|
||||
let v = m.apply_vec(mv.by);
|
||||
mv.by = if v.is_finite() { v } else { Vec2::ZERO };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the position of `k` by `by`: a text's, MText's or block reference's whole object, a
|
||||
/// multileader's landing and content (its arrowheads stay), a dimension's text. Other kinds stay.
|
||||
pub fn shift_position(k: &mut EntityKind, by: Vec2) {
|
||||
if !by.is_finite() || by == Vec2::ZERO {
|
||||
return;
|
||||
}
|
||||
let add = |p: &mut cadcraft_geom::Vec3| {
|
||||
p.x += by.x;
|
||||
p.y += by.y;
|
||||
};
|
||||
match k {
|
||||
EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_) => k.transform(&Mat3::translate(by)),
|
||||
EntityKind::MLeader(m) => {
|
||||
add(&mut m.landing);
|
||||
if let Some(t) = &mut m.text {
|
||||
add(&mut t.insert);
|
||||
}
|
||||
if let Some(b) = &mut m.block {
|
||||
add(&mut b.insert);
|
||||
}
|
||||
}
|
||||
EntityKind::Dimension(d) => {
|
||||
add(&mut d.text_mid);
|
||||
d.user_text_pos = true;
|
||||
d.block = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether grip `index` of `k` is its position grip: moving it moves what [`shift_position`]
|
||||
/// moves.
|
||||
pub fn is_position_grip(k: &EntityKind, index: usize) -> bool {
|
||||
match k {
|
||||
EntityKind::Text(_) | EntityKind::MText(_) => true,
|
||||
EntityKind::Insert(_) => index == 0,
|
||||
EntityKind::Dimension(_) => index == 3,
|
||||
EntityKind::MLeader(m) => index == m.leaders.iter().map(Vec::len).sum::<usize>(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How `e` draws in a view whose annotation scale is `view` (drawing units per paper unit). An
|
||||
@@ -139,14 +224,23 @@ pub fn anno_draw(e: &Entity, view: f64, all_visible: bool) -> AnnoDraw {
|
||||
return AnnoDraw::Plain;
|
||||
}
|
||||
if e.common.supports_factor(view) {
|
||||
return AnnoDraw::Scaled(if view.is_finite() && view > 0.0 { view } else { 1.0 });
|
||||
let factor = if view.is_finite() && view > 0.0 { view } else { 1.0 };
|
||||
return AnnoDraw::Scaled { factor, by: e.common.moved_at_factor(view) };
|
||||
}
|
||||
match e.common.anno_scales.first() {
|
||||
Some(s) if all_visible => AnnoDraw::Scaled(s.factor()),
|
||||
Some(s) if all_visible => AnnoDraw::Scaled { factor: s.factor(), by: e.common.moved_at(&s.name) },
|
||||
_ => AnnoDraw::Hidden,
|
||||
}
|
||||
}
|
||||
|
||||
/// `e` as it draws at annotation scale `f` with its position moved `by` there: [`anno_scaled`],
|
||||
/// then [`shift_position`].
|
||||
pub fn anno_placed(e: &Entity, f: f64, by: Vec2) -> Entity {
|
||||
let mut out = anno_scaled(e, f);
|
||||
shift_position(&mut out.kind, by);
|
||||
out
|
||||
}
|
||||
|
||||
/// `e` as it draws at annotation scale `f`: its paper sizes (text height and width, dimension
|
||||
/// overall scale, multileader arrow, landing and content, hatch pattern scale, block scale and
|
||||
/// attributes) multiplied by `f`. A dimension is drawn from its definition at that scale, not
|
||||
@@ -225,13 +319,44 @@ impl Drawing {
|
||||
/// (paper space shows every annotative object), elsewhere (model space, or an object not in
|
||||
/// the drawing yet) as [`anno_draw`] at the current annotation scale.
|
||||
pub fn anno_draw(&self, e: &Entity) -> AnnoDraw {
|
||||
self.anno_draw_in(e, None)
|
||||
}
|
||||
/// How top-level object `e` draws where it is edited: through an active viewport whose
|
||||
/// annotation scale is `view` (drawing units per paper unit, the viewport's scale, as the
|
||||
/// renderer draws model space there), else as [`Drawing::anno_draw`].
|
||||
pub fn anno_draw_in(&self, e: &Entity, view: Option<f64>) -> AnnoDraw {
|
||||
if !is_annotative(e) {
|
||||
return AnnoDraw::Plain;
|
||||
}
|
||||
if !self.model.contains(e.handle) && self.layouts.iter().any(|l| l.entities.contains(e.handle)) {
|
||||
return AnnoDraw::Scaled(1.0);
|
||||
return AnnoDraw::Scaled { factor: 1.0, by: e.common.moved_at_factor(1.0) };
|
||||
}
|
||||
let view = view.filter(|f| f.is_finite() && *f > 0.0).unwrap_or_else(|| self.current_anno_scale().factor());
|
||||
anno_draw(e, view, self.anno_all_visible())
|
||||
}
|
||||
/// The scale `e` shows at outside a viewport (see [`Drawing::anno_draw`]): its name and
|
||||
/// factor, `None` when `e` isn't annotative or doesn't show.
|
||||
pub fn anno_shown_scale(&self, e: &Entity) -> Option<AnnoScale> {
|
||||
self.anno_shown_scale_in(e, None)
|
||||
}
|
||||
/// The scale `e` shows at in view `view` (see [`Drawing::anno_draw_in`]).
|
||||
pub fn anno_shown_scale_in(&self, e: &Entity, view: Option<f64>) -> Option<AnnoScale> {
|
||||
match self.anno_draw_in(e, view) {
|
||||
AnnoDraw::Scaled { factor, .. } => e.common.anno_scales.iter().find(|s| s.has_factor(factor)).cloned(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `e` as it draws outside a viewport: an annotative object at its scale and position there,
|
||||
/// anything else (and a hidden annotative object) as stored.
|
||||
pub fn anno_shown(&self, e: &Entity) -> EntityKind {
|
||||
self.anno_shown_in(e, None)
|
||||
}
|
||||
/// `e` as it draws in view `view` (see [`Drawing::anno_draw_in`]).
|
||||
pub fn anno_shown_in(&self, e: &Entity, view: Option<f64>) -> EntityKind {
|
||||
match self.anno_draw_in(e, view) {
|
||||
AnnoDraw::Scaled { factor, by } => anno_placed(e, factor, by).kind,
|
||||
_ => e.kind.clone(),
|
||||
}
|
||||
anno_draw(e, self.current_anno_scale().factor(), self.anno_all_visible())
|
||||
}
|
||||
/// Whether new objects of this kind are annotative: text and MText with an annotative text
|
||||
/// style, dimensions with an annotative dimension style, multileaders with an annotative
|
||||
|
||||
@@ -98,6 +98,10 @@ pub struct Common {
|
||||
/// The annotation scales an annotative object supports (empty: not annotative).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub anno_scales: Vec<crate::AnnoScale>,
|
||||
/// Where an annotative object sits apart from its shared position at some of its scales
|
||||
/// (moved with its grips at that scale; ANNORESET clears them).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub anno_moves: Vec<crate::AnnoMove>,
|
||||
/// Other applications' extended data (xdata) as read from the drawing file: whole
|
||||
/// applications, each from its `1001` group on. It is part of the object, so a copy of the
|
||||
/// object (COPY, MIRROR, ARRAY, paste) carries it, as in AutoCAD.
|
||||
@@ -119,6 +123,7 @@ impl Default for Common {
|
||||
extrusion: Vec3::Z,
|
||||
plot_style: "ByLayer".into(),
|
||||
anno_scales: Vec::new(),
|
||||
anno_moves: Vec::new(),
|
||||
xdata: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,7 +645,9 @@ fn bounds_of<'a>(
|
||||
match d.anno_draw(e) {
|
||||
crate::AnnoDraw::Plain => {}
|
||||
crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
|
||||
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen),
|
||||
crate::AnnoDraw::Scaled { factor, by } => {
|
||||
return bounds_in(d, &crate::anno_placed(e, factor, by), 0, blocks, in_drawing, off_counts, frozen);
|
||||
}
|
||||
}
|
||||
}
|
||||
bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! objects show (ANNOALLVISIBLE) and the current annotation scale (CANNOSCALE with
|
||||
//! ANNOAUTOSCALE).
|
||||
|
||||
use cadcraft_doc::geom::Vec2;
|
||||
use cadcraft_doc::{AnnoScale, Drawing, EntityKind, Handle, MAX_SCALES, is_annotative};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -136,6 +137,7 @@ fn remove_scale(d: &mut Drawing, h: Handle, name: &str) -> Removed {
|
||||
return;
|
||||
}
|
||||
e.common.anno_scales.retain(|s| !s.name.eq_ignore_ascii_case(name));
|
||||
e.common.anno_moves.retain(|m| !m.scale.eq_ignore_ascii_case(name));
|
||||
r = Removed::Yes;
|
||||
});
|
||||
r
|
||||
@@ -216,8 +218,27 @@ fn with_handles(s: &Session, p: &Value, mut extra: Value) -> Value {
|
||||
|
||||
fn run_annoreset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (hs, _) = annotative_targets(s, p, "annoreset")?;
|
||||
// One position serves every scale of an object, so they are always in step.
|
||||
Ok(json!({ "objects": hs.len(), "message": format!("{} annotative object(s) synchronized", hs.len()) }))
|
||||
// Every scale goes where the object shows now (in the active viewport, at its scale): that
|
||||
// offset becomes the shared position.
|
||||
let view = s.anno_view();
|
||||
let d = s.doc_mut()?;
|
||||
let mut moved = 0;
|
||||
for h in &hs {
|
||||
let Some(e) = d.entity(*h) else { continue };
|
||||
if e.common.anno_moves.is_empty() || d.layer(&e.common.layer).is_some_and(|l| l.locked) {
|
||||
continue;
|
||||
}
|
||||
let by = match d.anno_draw_in(e, view) {
|
||||
cadcraft_doc::AnnoDraw::Scaled { by, .. } => by,
|
||||
_ => Vec2::ZERO,
|
||||
};
|
||||
d.modify_entity(*h, |e| {
|
||||
cadcraft_doc::shift_position(&mut e.kind, by);
|
||||
e.common.anno_moves.clear();
|
||||
})?;
|
||||
moved += 1;
|
||||
}
|
||||
Ok(json!({ "objects": hs.len(), "reset": moved, "message": format!("{} annotative object(s) synchronized", hs.len()) }))
|
||||
}
|
||||
|
||||
fn run_annoupdate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -86,6 +86,7 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result<Vec<Handle>> {
|
||||
let old_h = e.handle;
|
||||
let mut e = adopt(d, e, &renames);
|
||||
e.kind.transform(m);
|
||||
e.common.transform_moves(m);
|
||||
d.ensure_layer(&e.common.layer);
|
||||
out.push(e.handle);
|
||||
copies.push((old_h, e.handle));
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
//! `grip.*` commands: the undoable, scriptable form of grip editing (see `crate::grips`).
|
||||
|
||||
use cadcraft_doc::{Entity, EntityKind, Handle};
|
||||
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle};
|
||||
use cadcraft_geom::{Mat3, Vec2, Vec3};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::curves;
|
||||
use super::{CommandSpec, bad, bool_or, point_param, point_req, str_param, targets};
|
||||
|
||||
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, stretch_grip};
|
||||
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, shown_grips, stretch_shown};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -46,25 +46,28 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other("The object is on a locked layer.".into()));
|
||||
}
|
||||
let e = curves::entity(s, h)?;
|
||||
let k = stretch_grip(&e.kind, i, to).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
|
||||
let mut edits = vec![(h, k)];
|
||||
let view = s.anno_view();
|
||||
let doc = s.doc()?;
|
||||
let ne = stretch_shown(doc, &e, i, to, view).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
|
||||
let mut edits = vec![(h, ne)];
|
||||
// The other `handles` with a grip on the same point stretch with it (connected objects stay
|
||||
// connected); locked ones and edits that would be degenerate are left alone.
|
||||
let from = e.kind.grips().get(i).copied().unwrap_or(to);
|
||||
let from = shown_grips(doc, &e, view).get(i).copied().unwrap_or(to);
|
||||
let tol = 1e-9 * (1.0 + from.len());
|
||||
for o in targets(s, p)? {
|
||||
if o == h || edits.iter().any(|(x, _)| *x == o) || curves::is_locked(s, o) {
|
||||
continue;
|
||||
}
|
||||
let Ok(oe) = curves::entity(s, o) else { continue };
|
||||
if let Some(j) = oe.kind.grips().iter().position(|g| g.near(from, tol))
|
||||
&& let Some(k) = stretch_grip(&oe.kind, j, to)
|
||||
if let Some(j) = shown_grips(doc, &oe, view).iter().position(|g| g.near(from, tol))
|
||||
&& let Some(ne) = stretch_shown(doc, &oe, j, to, view)
|
||||
{
|
||||
edits.push((o, k));
|
||||
edits.push((o, ne));
|
||||
}
|
||||
}
|
||||
let d = s.doc_mut()?;
|
||||
for (o, k) in &mut edits {
|
||||
for (o, ne) in &mut edits {
|
||||
let (k, moves) = (&mut ne.kind, &ne.common.anno_moves);
|
||||
// A dimension's text moved by its grip: with DIMTMOVE 0 the dimension line follows.
|
||||
if let cadcraft_doc::EntityKind::Dimension(dm) = k
|
||||
&& let Some(cadcraft_doc::EntityKind::Dimension(old)) = d.entity(*o).map(|e| &e.kind)
|
||||
@@ -73,14 +76,17 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
|
||||
let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
|
||||
st.follow_text(dm, d.header.f64("DIMSCALE", 1.0));
|
||||
}
|
||||
d.modify_entity(*o, |e| e.kind = k.clone())?;
|
||||
d.modify_entity(*o, |e| {
|
||||
e.kind = k.clone();
|
||||
e.common.anno_moves = moves.clone();
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// Z coordinate of grip `index` on `kind` (matching `EntityKind::grips()` order), when the
|
||||
/// entity stores a 3D position for that grip.
|
||||
pub(super) fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
|
||||
fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
|
||||
let text_z = |t: &cadcraft_doc::Text| match (t.halign, t.valign) {
|
||||
(cadcraft_doc::HAlign::Left, cadcraft_doc::VAlign::Baseline) | (cadcraft_doc::HAlign::Aligned | cadcraft_doc::HAlign::Fit, _) => t.insert.z,
|
||||
_ => t.align_pt.unwrap_or(t.insert).z,
|
||||
@@ -151,10 +157,17 @@ fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2>
|
||||
.or_else(|| hs.first().copied())
|
||||
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
|
||||
let i = index_param(cmd, p)?;
|
||||
let g = curves::entity(s, h)?.kind.grips();
|
||||
let g = shown_grips(s.doc()?, &curves::entity(s, h)?, s.anno_view());
|
||||
g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))
|
||||
}
|
||||
|
||||
/// The displayed grip's planar point and its Z, when the entity has one.
|
||||
pub(super) fn shown_grip_location(d: &Drawing, e: &Entity, index: usize, view: Option<f64>) -> Option<(Vec2, Option<f64>)> {
|
||||
let kind = d.anno_shown_in(e, view);
|
||||
let point = kind.grips().get(index).copied()?;
|
||||
Some((point, grip_z(&kind, index)))
|
||||
}
|
||||
|
||||
/// 3D base point for SCALE: explicit `base` (with optional Z or ELEVATION), or the selected grip's
|
||||
/// full 3D position so the grip stays stationary in all three coordinates.
|
||||
fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec3> {
|
||||
@@ -169,8 +182,8 @@ fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec
|
||||
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
|
||||
let i = index_param(cmd, p)?;
|
||||
let e = curves::entity(s, h)?;
|
||||
let g = e.kind.grips().get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))?;
|
||||
Ok(match grip_z(&e.kind, i) {
|
||||
let (g, z) = shown_grip_location(s.doc()?, &e, i, s.anno_view()).ok_or_else(|| bad(cmd, "no such grip"))?;
|
||||
Ok(match z {
|
||||
Some(z) => Vec3::new(g.x, g.y, z),
|
||||
None => super::modify::at_elevation(s, g),
|
||||
})
|
||||
@@ -201,7 +214,7 @@ fn run_grip_stretch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => {
|
||||
let base = match point_param(p, "base") {
|
||||
Some(b) => b,
|
||||
None => curves::entity(s, h0)?.kind.grips().get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
|
||||
None => shown_grips(s.doc()?, &curves::entity(s, h0)?, s.anno_view()).get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
|
||||
};
|
||||
point_req(cmd, p, "to")? - base
|
||||
}
|
||||
@@ -245,8 +258,9 @@ const MAX_GRIPS: usize = 1000;
|
||||
/// The objects as they'd be after moving the grips `hot` by `delta`, with the grips of `others`
|
||||
/// that sit on a hot grip's point (connected objects stay connected). Locked objects and edits
|
||||
/// that would be degenerate are left out; several hot grips of one object move together.
|
||||
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, EntityKind)> {
|
||||
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, Entity)> {
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
let view = s.anno_view();
|
||||
// Every grip to move, per object, with its target point.
|
||||
let mut moves: Vec<(Handle, Vec<(usize, Vec2)>)> = Vec::new();
|
||||
let mut add = |h: Handle, i: usize, to: Vec2| match moves.iter_mut().find(|(x, _)| *x == h) {
|
||||
@@ -258,14 +272,14 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
|
||||
None => moves.push((h, vec![(i, to)])),
|
||||
};
|
||||
for &(h, i) in hot.iter().take(MAX_GRIPS) {
|
||||
let Some(from) = d.entity(h).and_then(|e| e.kind.grips().get(i).copied()) else { continue };
|
||||
let Some(from) = d.entity(h).and_then(|e| shown_grips(d, e, view).get(i).copied()) else { continue };
|
||||
add(h, i, from + delta);
|
||||
let tol = 1e-9 * (1.0 + from.len());
|
||||
for &o in others.iter().take(MAX_GRIPS) {
|
||||
if o == h {
|
||||
continue;
|
||||
}
|
||||
if let Some(j) = d.entity(o).and_then(|e| e.kind.grips().iter().position(|g| g.near(from, tol))) {
|
||||
if let Some(j) = d.entity(o).and_then(|e| shown_grips(d, e, view).iter().position(|g| g.near(from, tol))) {
|
||||
add(o, j, from + delta);
|
||||
}
|
||||
}
|
||||
@@ -276,16 +290,16 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
|
||||
continue;
|
||||
}
|
||||
let Some(e) = d.entity(h) else { continue };
|
||||
let mut k = e.kind.clone();
|
||||
let mut ne = (**e).clone();
|
||||
let mut changed = false;
|
||||
for (i, to) in mv {
|
||||
if let Some(nk) = stretch_grip(&k, i, to) {
|
||||
k = nk;
|
||||
if let Some(n) = stretch_shown(d, &ne, i, to, view) {
|
||||
ne = n;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
out.push((h, k));
|
||||
out.push((h, ne));
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -297,16 +311,19 @@ pub(super) fn stretch_grips(s: &mut Session, hot: &[(Handle, usize)], others: &[
|
||||
let edits = stretched(s, hot, others, delta);
|
||||
let d = s.doc_mut()?;
|
||||
let mut out = Vec::new();
|
||||
for (h, k) in edits {
|
||||
for (h, ne) in edits {
|
||||
if copy {
|
||||
let (Some(sp), Some(e)) = (d.space_of(h), d.entity(h).map(|e| (**e).clone())) else { continue };
|
||||
let Some(sp) = d.space_of(h) else { continue };
|
||||
let nh = d.new_handle();
|
||||
if let Some(st) = d.space_mut(&sp) {
|
||||
st.push(Entity { handle: nh, kind: k, ..e });
|
||||
st.push(Entity { handle: nh, ..ne });
|
||||
out.push(nh);
|
||||
}
|
||||
} else {
|
||||
d.modify_entity(h, |e| e.kind = k)?;
|
||||
d.modify_entity(h, |e| {
|
||||
e.kind = ne.kind;
|
||||
e.common.anno_moves = ne.common.anno_moves;
|
||||
})?;
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,14 +104,16 @@ impl GripEdit {
|
||||
if self.hot.contains(&(h, i)) || self.hot.len() >= MAX_HOT {
|
||||
return Ok(());
|
||||
}
|
||||
let p = s.grips_of(h)?.get(i).copied().ok_or_else(|| other("no such grip"))?;
|
||||
let d = s.doc()?;
|
||||
let e = d.entity(h).ok_or_else(|| other("no such object"))?;
|
||||
let (p, z) = super::gripcmds::shown_grip_location(d, e, i, s.anno_view()).ok_or_else(|| other("no such grip"))?;
|
||||
// After the lookup: a missing object or grip stays the error it was.
|
||||
if !shown(s, h) {
|
||||
return Ok(());
|
||||
}
|
||||
if self.hot.is_empty() {
|
||||
self.base = p;
|
||||
self.base_z = s.doc().ok().and_then(|d| d.entity(h)).and_then(|e| super::gripcmds::grip_z(&e.kind, i));
|
||||
self.base_z = z;
|
||||
self.targets.push(h);
|
||||
self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x)));
|
||||
} else if !self.targets.contains(&h) {
|
||||
@@ -131,7 +133,7 @@ impl GripEdit {
|
||||
continue;
|
||||
}
|
||||
let Some(e) = st.doc.entity(h).filter(|e| st.shows(e)) else { continue };
|
||||
let gs = e.kind.grips();
|
||||
let gs = crate::grips::shown_grips(&st.doc, e, s.anno_view());
|
||||
// The nearest grip of this object within the tolerance.
|
||||
let best = gs
|
||||
.iter()
|
||||
@@ -491,7 +493,11 @@ impl Interactive for GripEdit {
|
||||
};
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
let mut out: Vec<EntityKind> = if self.mode == GripMode::Stretch {
|
||||
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base).into_iter().take(500).map(|(_, k)| k).collect()
|
||||
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base)
|
||||
.into_iter()
|
||||
.take(500)
|
||||
.map(|(_, e)| d.anno_shown_in(&e, s.anno_view()))
|
||||
.collect()
|
||||
} else {
|
||||
match self.matrix(c) {
|
||||
Some(m) => self
|
||||
|
||||
@@ -190,10 +190,11 @@ pub(crate) fn explode_kind(d: &cadcraft_doc::Drawing, e: &Entity) -> Option<Vec<
|
||||
// An annotative object explodes into plain objects as it draws at the current annotation scale.
|
||||
if cadcraft_doc::is_annotative(e) {
|
||||
let mut se = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) => cadcraft_doc::anno_scaled(e, f),
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } => cadcraft_doc::anno_placed(e, factor, by),
|
||||
_ => e.clone(),
|
||||
};
|
||||
se.common.anno_scales.clear();
|
||||
se.common.anno_moves.clear();
|
||||
return explode_kind(d, &se);
|
||||
}
|
||||
match &e.kind {
|
||||
|
||||
@@ -7,7 +7,10 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, er
|
||||
|
||||
pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Vec<Handle>> {
|
||||
refuse_ole_frames(s, hs, m, copy)?;
|
||||
edit_entities(s, hs, copy, |e| e.kind.transform(m))
|
||||
edit_entities(s, hs, copy, |e| {
|
||||
e.kind.transform(m);
|
||||
e.common.transform_moves(m);
|
||||
})
|
||||
}
|
||||
|
||||
/// MIRROR's default hatch policy retains the fill direction while reflecting its boundary.
|
||||
@@ -40,6 +43,7 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64,
|
||||
refuse_ole_frames(s, hs, &m, copy)?;
|
||||
edit_entities(s, hs, copy, |e| {
|
||||
e.kind.transform(&m);
|
||||
e.common.transform_moves(&m);
|
||||
e.kind.scale_heights(base.z, f);
|
||||
e.common.thickness *= f;
|
||||
})
|
||||
|
||||
@@ -202,6 +202,7 @@ fn chspace(s: &mut Session, hs: &[Handle], to: Option<&str>, vp: Option<Handle>)
|
||||
}
|
||||
let mut e = e;
|
||||
e.kind.transform(&m);
|
||||
e.common.transform_moves(&m);
|
||||
d.remove_entity(*h);
|
||||
if let Some(st) = d.space_mut(&target) {
|
||||
st.push(e);
|
||||
|
||||
@@ -70,8 +70,8 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
|
||||
// Annotative text and dimensions are drawn scaled to the current annotation scale: the box
|
||||
// follows what is drawn. Multiline text keeps its stored height (it is written back from it).
|
||||
let scaled = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
|
||||
Some(cadcraft_doc::anno_scaled(e, f))
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
|
||||
Some(cadcraft_doc::anno_placed(e, factor, by))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -171,6 +171,12 @@ impl DocState {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// The annotation scale model space is edited at in the active MSPACE viewport: the
|
||||
/// viewport's scale (drawing units per paper unit, as the renderer draws it there); `None`
|
||||
/// outside one (the current annotation scale applies).
|
||||
pub fn anno_view(&self) -> Option<f64> {
|
||||
self.active_viewport().map(|(_, v)| v.view_height / v.height).filter(|f| f.is_finite() && *f > 0.0)
|
||||
}
|
||||
/// The layers frozen in the active MSPACE viewport (VPLAYER, "VP Freeze"): that viewport does
|
||||
/// not draw their objects, so picks, selections and grips made through it leave them out.
|
||||
/// Empty in paper space and on the Model tab.
|
||||
|
||||
@@ -185,8 +185,9 @@ pub fn grip_dims(s: &Session) -> Vec<GripDim> {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some((h, i)) = s.current_prompt().and_then(|p| p.grip) else { return Vec::new() };
|
||||
let Some(e) = s.doc().ok().and_then(|d| d.entity(h)) else { return Vec::new() };
|
||||
let all = dims_of(&e.kind, i);
|
||||
let Ok(d) = s.doc() else { return Vec::new() };
|
||||
let Some(e) = d.entity(h) else { return Vec::new() };
|
||||
let all = dims_of(&d.anno_shown_in(e, s.anno_view()), i);
|
||||
let st = &s.settings;
|
||||
match st.dyndivis {
|
||||
0 => all.into_iter().take(1).collect(),
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! The UI calls [`Session::grip_edit`]; every edit runs through a `grip.*` command so it is
|
||||
//! undoable and reachable from scripts, the control channel and MCP.
|
||||
|
||||
use cadcraft_doc::{DimKind, EntityKind, Handle, LwPolyline};
|
||||
use cadcraft_doc::{DimKind, Drawing, Entity, EntityKind, Handle, LwPolyline};
|
||||
use cadcraft_geom::{Arc, EPS, Mat3, Polyline, Vec2, Vec3, norm_angle};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
@@ -564,10 +564,59 @@ impl Session {
|
||||
|
||||
/// Grip points of an object (the indices `grip_edit` takes).
|
||||
pub fn grips_of(&self, handle: Handle) -> Result<Vec<Vec2>> {
|
||||
self.doc()?.entity(handle).map(|e| e.kind.grips()).ok_or_else(|| EngineError::Other("no such object".into()))
|
||||
let d = self.doc()?;
|
||||
d.entity(handle).map(|e| shown_grips(d, e, self.anno_view())).ok_or_else(|| EngineError::Other("no such object".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The grip points of `e` as it shows (the indices `grip_edit` takes): an annotative object's at
|
||||
/// the annotation scale it shows at and its position there. `view`: the active viewport's scale
|
||||
/// in MSPACE ([`crate::DocState::anno_view`]), else the current annotation scale applies.
|
||||
pub fn shown_grips(d: &Drawing, e: &Entity, view: Option<f64>) -> Vec<Vec2> {
|
||||
d.anno_shown_in(e, view).grips()
|
||||
}
|
||||
|
||||
/// `e` with grip `index` of [`shown_grips`] moved to `to`, or `None` when that grip can't move
|
||||
/// there. An annotative object's position grip moves it at the scale it shows at only when it
|
||||
/// supports several scales; its other grips change its shape at every scale (the edit is taken
|
||||
/// back to paper size).
|
||||
pub fn stretch_shown(d: &Drawing, e: &Entity, index: usize, to: Vec2, view: Option<f64>) -> Option<Entity> {
|
||||
let with = |kind: EntityKind| Some(Entity { kind, ..e.clone() });
|
||||
let (Some(scale), cadcraft_doc::AnnoDraw::Scaled { factor, by }) = (d.anno_shown_scale_in(e, view), d.anno_draw_in(e, view)) else {
|
||||
return with(stretch_grip(&e.kind, index, to)?);
|
||||
};
|
||||
let shown = cadcraft_doc::anno_placed(e, factor, by).kind;
|
||||
let from = *shown.grips().get(index)?;
|
||||
let delta = to - from;
|
||||
if !delta.is_finite() {
|
||||
return None;
|
||||
}
|
||||
if cadcraft_doc::is_position_grip(&e.kind, index) {
|
||||
if e.common.anno_scales.len() > 1 {
|
||||
let mut out = e.clone();
|
||||
out.common.move_at(&scale.name, delta);
|
||||
return Some(out);
|
||||
}
|
||||
let stored = *e.kind.grips().get(index)?;
|
||||
return with(stretch_grip(&e.kind, index, stored + delta)?);
|
||||
}
|
||||
// A shape grip: stretch the object as it shows, then take it back to paper size.
|
||||
let mut k = stretch_grip(&shown, index, to)?;
|
||||
cadcraft_doc::shift_position(&mut k, -by);
|
||||
let k = match (k, &e.kind) {
|
||||
(EntityKind::Dimension(mut dm), EntityKind::Dimension(old)) => {
|
||||
// A dimension's geometry isn't scaled: only its style scale was.
|
||||
dm.overrides = old.overrides.clone();
|
||||
if by != Vec2::ZERO {
|
||||
dm.user_text_pos = old.user_text_pos;
|
||||
}
|
||||
EntityKind::Dimension(dm)
|
||||
}
|
||||
(k, _) => cadcraft_doc::anno_scaled(&Entity { kind: k, ..e.clone() }, 1.0 / factor).kind,
|
||||
};
|
||||
with(k)
|
||||
}
|
||||
|
||||
/// Polyline helper kept public for the UI: segment midpoints are grips too.
|
||||
pub fn polyline_grip_count(p: &LwPolyline) -> usize {
|
||||
p.vertices.len() + Polyline { vertices: p.vertices.clone(), closed: p.closed }.segments().len().min(p.vertices.len())
|
||||
|
||||
@@ -416,6 +416,11 @@ impl Session {
|
||||
Ok(h)
|
||||
}
|
||||
|
||||
/// The annotation scale of the active MSPACE viewport ([`DocState::anno_view`]).
|
||||
pub fn anno_view(&self) -> Option<f64> {
|
||||
self.state().ok().and_then(DocState::anno_view)
|
||||
}
|
||||
|
||||
/// World units per pixel at the current view.
|
||||
pub fn pixel_size(&self) -> f64 {
|
||||
let v = self.state().map(DocState::view).unwrap_or_default();
|
||||
|
||||
@@ -360,15 +360,16 @@ fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> {
|
||||
if !is_blank_mtext(text) {
|
||||
return None;
|
||||
}
|
||||
let f = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Plain => 1.0,
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f,
|
||||
cadcraft_doc::AnnoDraw::Scaled(_) => 1.0,
|
||||
// As it is drawn: at the current scale, where that scale places it.
|
||||
let (f, by) = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Plain => (1.0, Vec2::ZERO),
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } if factor.is_finite() && factor > 0.0 => (factor, by),
|
||||
cadcraft_doc::AnnoDraw::Scaled { .. } => (1.0, Vec2::ZERO),
|
||||
cadcraft_doc::AnnoDraw::Hidden => return None,
|
||||
};
|
||||
let scaled;
|
||||
let e = if f != 1.0 {
|
||||
scaled = cadcraft_doc::anno_scaled(e, f);
|
||||
let e = if f != 1.0 || by != Vec2::ZERO {
|
||||
scaled = cadcraft_doc::anno_placed(e, f, by);
|
||||
&scaled
|
||||
} else {
|
||||
e
|
||||
@@ -497,8 +498,8 @@ fn drawn_text(d: &Drawing, e: &Entity) -> Option<Vec<Vec<Vec2>>> {
|
||||
let e = match d.anno_draw(e) {
|
||||
cadcraft_doc::AnnoDraw::Plain => e,
|
||||
cadcraft_doc::AnnoDraw::Hidden => return None,
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) => {
|
||||
scaled = cadcraft_doc::anno_scaled(e, f);
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } => {
|
||||
scaled = cadcraft_doc::anno_placed(e, factor, by);
|
||||
&scaled
|
||||
}
|
||||
};
|
||||
|
||||
@@ -81,7 +81,7 @@ fn unsupported_scale_hides_unless_annoallvisible() {
|
||||
let (mut s, h) = with_text();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:20"));
|
||||
// ANNOALLVISIBLE 1 (the default): shown, at the object's own scale.
|
||||
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled(1.0));
|
||||
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled { factor: 1.0, by: cadcraft_engine::geom::Vec2::ZERO });
|
||||
assert!(drawn_height(s.doc().unwrap(), h).is_some());
|
||||
s.execute("annovisible.current", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().header.i64("ANNOALLVISIBLE", 1), 0);
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
//! An annotative object can sit somewhere else at one of its scales: its grips move it at the
|
||||
//! current annotation scale only (when it supports several), MOVE and ROTATE move every scale,
|
||||
//! and ANNORESET puts every scale back where the current one is.
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{AnnoDraw, Entity, EntityKind, Handle};
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn setvar(s: &mut Session, name: &str, value: Value) {
|
||||
s.execute("setvar", &json!({ "name": name, "value": value })).unwrap();
|
||||
}
|
||||
|
||||
fn handle(r: &Value) -> Handle {
|
||||
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).and_then(Handle::parse_hex).unwrap()
|
||||
}
|
||||
|
||||
fn entity(s: &Session, h: Handle) -> Entity {
|
||||
(**s.doc().unwrap().entity(h).unwrap()).clone()
|
||||
}
|
||||
|
||||
/// Annotative text at the origin supporting 1:1 and 1:50, with 1:50 current.
|
||||
fn two_scales() -> (Session, Handle) {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
|
||||
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).unwrap();
|
||||
(s, h)
|
||||
}
|
||||
|
||||
/// Where `h` shows at annotation scale `name`.
|
||||
fn shown_at(s: &mut Session, h: Handle, name: &str) -> Vec2 {
|
||||
setvar(s, "CANNOSCALE", json!(name));
|
||||
let d = s.doc().unwrap();
|
||||
match d.anno_shown(d.entity(h).unwrap()) {
|
||||
EntityKind::Text(t) => t.insert.xy(),
|
||||
EntityKind::MText(t) => t.insert.xy(),
|
||||
EntityKind::MLeader(m) => m.landing.xy(),
|
||||
EntityKind::Dimension(dm) => dm.text_mid.xy(),
|
||||
k => panic!("{k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn near(a: Vec2, b: Vec2) -> bool {
|
||||
a.dist(b) < 1e-9
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grip_moves_text_at_the_current_scale_only() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
// The grips show where the object is.
|
||||
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::ZERO));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grip_scale_keeps_the_displayed_annotation_pivot_and_its_elevation() {
|
||||
let (mut s, h) = two_scales();
|
||||
let (z, other_z) = (7.0, 2.0);
|
||||
s.doc_mut().unwrap().header.set_f64("ELEVATION", other_z);
|
||||
s.doc_mut()
|
||||
.unwrap()
|
||||
.modify_entity(h, |e| {
|
||||
let EntityKind::Text(t) = &mut e.kind else { panic!("expected text") };
|
||||
t.insert.z = z;
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
let pivot = s.grips_of(h).unwrap()[0];
|
||||
assert!(near(pivot, Vec2::new(5.0, 5.0)));
|
||||
let EntityKind::Text(before) = entity(&s, h).kind else { panic!("expected text") };
|
||||
s.execute("grip.scale", &json!({ "handles": [h.hex()], "baseHandle": h.hex(), "index": 0, "factor": 2.0 })).unwrap();
|
||||
let EntityKind::Text(after) = entity(&s, h).kind else { panic!("expected text") };
|
||||
assert!(near(s.grips_of(h).unwrap()[0], pivot), "the displayed grip is stationary");
|
||||
assert!((after.insert.z - z).abs() < 1e-9, "the selected grip's Z is stationary, not ELEVATION");
|
||||
assert!((after.height - 2.0 * before.height).abs() < 1e-9, "the scale operation actually took effect");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_takes_a_move_at_one_scale_back() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
assert_eq!(entity(&s, h).common.anno_moves.len(), 1);
|
||||
s.execute("undo", &json!({})).unwrap();
|
||||
assert!(entity(&s, h).common.anno_moves.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_and_rotate_carry_every_scale() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
s.execute("move", &json!({ "handles": [h.hex()], "delta": [1, 0] })).unwrap();
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(6.0, 5.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(1.0, 0.0)));
|
||||
s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 90 })).unwrap();
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(-5.0, 6.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(0.0, 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn annoreset_puts_every_scale_at_the_current_one() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
let r = s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
assert_eq!(r["reset"], 1, "{r}");
|
||||
assert!(entity(&s, h).common.anno_moves.is_empty());
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(5.0, 5.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_scale_drops_its_position() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
s.execute("objectscale", &json!({ "handles": [h.hex()], "delete": "1:50" })).unwrap();
|
||||
assert!(entity(&s, h).common.anno_moves.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_with_one_scale_moves_everywhere() {
|
||||
let mut s = Session::new();
|
||||
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
let e = entity(&s, h);
|
||||
assert!(e.common.anno_moves.is_empty());
|
||||
let EntityKind::Text(t) = &e.kind else { panic!() };
|
||||
assert!(near(t.insert.xy(), Vec2::new(5.0, 5.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multileader_moves_its_content_and_keeps_its_arrowhead() {
|
||||
let mut s = Session::new();
|
||||
s.execute("mleaderstyle", &json!({ "name": "Anno", "annotative": true })).unwrap();
|
||||
let h = handle(&s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap());
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).unwrap();
|
||||
let EntityKind::MLeader(m) = entity(&s, h).kind else { panic!() };
|
||||
let landing = m.leaders.iter().map(Vec::len).sum::<usize>();
|
||||
let to = m.landing.xy() + Vec2::new(2.0, 1.0);
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": landing, "to": [to.x, to.y] })).unwrap();
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), to));
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), m.landing.xy()));
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
let d = s.doc().unwrap();
|
||||
let EntityKind::MLeader(shown) = d.anno_shown(d.entity(h).unwrap()) else { panic!() };
|
||||
assert!(near(shown.leaders[0][0].xy(), Vec2::ZERO), "the arrowhead stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dimension_moves_its_text_at_one_scale() {
|
||||
let mut s = Session::new();
|
||||
s.execute("dimstyle", &json!({ "name": "Anno", "annotative": true, "current": true })).unwrap();
|
||||
let h = handle(&s.execute("dimaligned", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 2] })).unwrap());
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:2"));
|
||||
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:2" })).unwrap();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 3, "to": [20, 20] })).unwrap();
|
||||
assert!(near(shown_at(&mut s, h, "1:2"), Vec2::new(20.0, 20.0)));
|
||||
let e = entity(&s, h);
|
||||
let EntityKind::Dimension(dm) = &e.kind else { panic!() };
|
||||
assert!(!near(dm.text_mid.xy(), Vec2::new(20.0, 20.0)), "the shared text position stays");
|
||||
assert_eq!(e.common.anno_moves.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shown_draws_through_the_offset() {
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:50"));
|
||||
let d = s.doc().unwrap();
|
||||
assert!(matches!(d.anno_draw(d.entity(h).unwrap()), AnnoDraw::Scaled { by, .. } if near(by, Vec2::new(5.0, 5.0))));
|
||||
let b = cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0);
|
||||
assert!(b.min.x > 4.0 && b.min.y > 4.0, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_offsets_never_panic() {
|
||||
let (mut s, h) = two_scales();
|
||||
for to in [json!([1e308, -1e308]), json!([f64::MAX, 0]), json!(["x", 1])] {
|
||||
let _ = s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": to }));
|
||||
}
|
||||
s.doc_mut().unwrap().modify_entity(h, |e| e.common.move_at("1:50", Vec2::new(f64::NAN, 1.0))).unwrap();
|
||||
let _ = s.execute("annoreset", &json!({ "handles": [h.hex()] }));
|
||||
let _ = s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 1e300 }));
|
||||
let d = s.doc().unwrap();
|
||||
let _ = cadcraft_engine::render::build(d, &cadcraft_engine::doc::Space::Model, &Default::default());
|
||||
let _ = bounds(d, h);
|
||||
}
|
||||
|
||||
fn bounds(d: &cadcraft_engine::doc::Drawing, h: Handle) -> cadcraft_engine::geom::Bounds2 {
|
||||
cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_a_viewport_grips_and_annoreset_use_the_viewport_s_scale() {
|
||||
// The text moved at 1:50; CANNOSCALE is 1:1 while a 1:50 viewport is active (MSPACE): the
|
||||
// grips show where the viewport draws it, a grip moves it at 1:50, ANNORESET takes 1:50's place.
|
||||
let (mut s, h) = two_scales();
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
|
||||
setvar(&mut s, "CANNOSCALE", json!("1:1"));
|
||||
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
|
||||
let vp = s.execute("mview", &json!({ "p1": [0, 0], "p2": [200, 100] })).unwrap();
|
||||
let vh = vp["viewports"][0].as_str().and_then(Handle::parse_hex).unwrap();
|
||||
s.execute("viewport.set", &json!({ "handle": vh.hex(), "scale": "1:50", "center": [0, 0] })).unwrap();
|
||||
s.execute("mspace", &json!({ "handle": vh.hex() })).unwrap();
|
||||
assert!((s.anno_view().unwrap() - 50.0).abs() < 1e-9);
|
||||
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)), "{:?}", s.grips_of(h));
|
||||
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [7, 7] })).unwrap();
|
||||
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(7.0, 7.0)));
|
||||
s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
|
||||
s.execute("pspace", &json!({})).unwrap();
|
||||
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
|
||||
// 1:1 was never moved by the grips, and now sits where 1:50 is.
|
||||
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(7.0, 7.0)));
|
||||
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(7.0, 7.0)));
|
||||
}
|
||||
@@ -6,6 +6,7 @@ mod angle_prompts;
|
||||
mod angle_settings;
|
||||
mod annotate_options;
|
||||
mod annotative;
|
||||
mod annotative_positions;
|
||||
mod arc_ctrl_direction;
|
||||
mod array_commands;
|
||||
mod array_counts;
|
||||
|
||||
@@ -11,8 +11,9 @@
|
||||
//! CADCraft keeps an annotative object at paper size with the list of scales it supports
|
||||
//! ([`cadcraft_doc::Common::anno_scales`]). It writes the object at its default scale with a
|
||||
//! context per scale ([`plan`], [`objects`]), and reads the scales and paper size back from the
|
||||
//! contexts ([`resolve`]). An object's position at each scale is the one the scale gives it:
|
||||
//! AutoCAD lets a context move an object at one scale only, which CADCraft doesn't model.
|
||||
//! contexts ([`resolve`]). A context can place the object somewhere else at its scale (moved with
|
||||
//! grips at that scale in AutoCAD or CADCraft): that is the object's offset at the scale
|
||||
//! ([`cadcraft_doc::AnnoMove`]), written into and read back from the context's position.
|
||||
//!
|
||||
//! Objects inside block definitions are left alone, and files older than AutoCAD 2007's format
|
||||
//! (before annotation scaling) don't get contexts.
|
||||
@@ -67,8 +68,16 @@ fn by_alignment(t: &Text) -> bool {
|
||||
|
||||
/// `e` at annotation scale `f`, as its groups are written there: sizes scaled (see
|
||||
/// [`cadcraft_doc::anno_scaled`]) and justified text's start point moved with its size about its
|
||||
/// alignment point. A dimension's definition gets that scale (DIMSCALE).
|
||||
/// alignment point. A dimension's definition gets that scale (DIMSCALE). The object's offset at
|
||||
/// that scale moves it there.
|
||||
pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity {
|
||||
let mut out = shared_at_scale(e, f);
|
||||
cadcraft_doc::shift_position(&mut out.kind, e.common.moved_at_factor(f));
|
||||
out
|
||||
}
|
||||
|
||||
/// [`at_scale`] at the object's shared position (without its offset there).
|
||||
fn shared_at_scale(e: &Entity, f: f64) -> Entity {
|
||||
let mut out = cadcraft_doc::anno_scaled(e, f);
|
||||
if let (EntityKind::Text(t), EntityKind::Text(paper)) = (&mut out.kind, &e.kind)
|
||||
&& by_alignment(paper)
|
||||
@@ -79,6 +88,47 @@ pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity {
|
||||
out
|
||||
}
|
||||
|
||||
/// The point that places `e` (as written at some scale): a text's start or alignment point, an
|
||||
/// MText's insertion point, a dimension's text position, a multileader's landing.
|
||||
fn anchor(d: &Drawing, e: &Entity) -> Option<cadcraft_geom::Vec2> {
|
||||
let p = match &e.kind {
|
||||
EntityKind::Text(t) if by_alignment(t) => t.align_pt?.xy(),
|
||||
EntityKind::Text(t) => t.insert.xy(),
|
||||
EntityKind::MText(t) => t.insert.xy(),
|
||||
EntityKind::Dimension(dm) if dm.user_text_pos => dm.text_mid.xy(),
|
||||
EntityKind::Dimension(dm) => cadcraft_render::dimension_in(d, dm).text_pos,
|
||||
EntityKind::MLeader(m) => m.landing.xy(),
|
||||
_ => return None,
|
||||
};
|
||||
p.is_finite().then_some(p)
|
||||
}
|
||||
|
||||
/// The same point as a context of `e` holds it (`g`: the context's groups after its SCALE
|
||||
/// handle).
|
||||
fn context_anchor(e: &Entity, g: &[Tag]) -> Option<cadcraft_geom::Vec2> {
|
||||
let xy = |code: i32| -> Option<cadcraft_geom::Vec2> {
|
||||
let i = g.iter().position(|t| t.code == code)?;
|
||||
let y = g.get(i + 1).filter(|t| t.code == code + 10)?;
|
||||
let v = cadcraft_geom::Vec2::new(g.get(i)?.f64(), y.f64());
|
||||
v.is_finite().then_some(v)
|
||||
};
|
||||
match &e.kind {
|
||||
EntityKind::Text(t) if by_alignment(t) => xy(11),
|
||||
EntityKind::Text(_) => xy(10),
|
||||
EntityKind::MText(_) => xy(11),
|
||||
// Only a text the user placed (294 = 0) holds its own position.
|
||||
EntityKind::Dimension(_) => g.iter().find(|t| t.code == 294).is_some_and(|t| t.i64() == 0).then(|| xy(10)).flatten(),
|
||||
EntityKind::MLeader(_) => {
|
||||
let mut tags = vec![Tag::s(100, "AcDbMLeader"), Tag::s(300, "CONTEXT_DATA{")];
|
||||
tags.extend(g.iter().cloned());
|
||||
tags.push(Tag::s(301, "}"));
|
||||
let p = crate::dxf_mleader::read(&tags).landing.xy();
|
||||
p.is_finite().then_some(p)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One context: its handle, the SCALE object's handle and the scale.
|
||||
pub(crate) struct Context {
|
||||
handle: String,
|
||||
@@ -347,6 +397,16 @@ pub(crate) fn mleader_at(tags: &mut [Tag], f: f64) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A multileader's groups (as [`crate::dxf_mleader::entity_tags`] writes them) marked annotative:
|
||||
/// the entity's "enable annotation scale" (its 293, after the `CONTEXT_DATA{` block) is on.
|
||||
/// Without it AutoCAD keeps the contexts but its ANNORESET passes the multileader over.
|
||||
pub(crate) fn mleader_annotative(tags: &mut [Tag]) {
|
||||
let Some(close) = tags.iter().position(|t| t.code == 301) else { return };
|
||||
if let Some(t) = tags.iter_mut().skip(close + 1).find(|t| t.code == 293) {
|
||||
*t = Tag::i(293, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Reading
|
||||
|
||||
@@ -422,6 +482,7 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
.and_then(|s| objs.get(&s));
|
||||
let Some((_, dict)) = dict else { continue };
|
||||
let mut list: Vec<(AnnoScale, bool)> = Vec::new();
|
||||
let mut placed: Vec<(String, f64, cadcraft_geom::Vec2)> = Vec::new();
|
||||
for c in all_entries(dict) {
|
||||
let Some((_, t)) = objs.get(&c).filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) else { continue };
|
||||
let g = own(t);
|
||||
@@ -431,6 +492,10 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
&& !list.iter().any(|(x, _)| x.name.eq_ignore_ascii_case(&s.name))
|
||||
{
|
||||
list.push((s.clone(), default));
|
||||
let after = g.iter().position(|t| t.code == 340).map_or(&[][..], |i| g.get(i + 1..).unwrap_or(&[]));
|
||||
if let Some(at) = context_anchor(e, after) {
|
||||
placed.push((s.name.clone(), s.factor(), at));
|
||||
}
|
||||
}
|
||||
}
|
||||
if list.is_empty() {
|
||||
@@ -443,6 +508,23 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
|
||||
e.common.anno_scales = list;
|
||||
to_paper(e, f);
|
||||
});
|
||||
// A context placing the object elsewhere than its scale would: its offset there.
|
||||
let Some(e) = d.entity(h).map(|e| (**e).clone()) else { continue };
|
||||
let moves: Vec<(String, cadcraft_geom::Vec2)> = placed
|
||||
.iter()
|
||||
.filter_map(|(name, f, at)| {
|
||||
let by = *at - anchor(d, &shared_at_scale(&e, *f))?;
|
||||
let tol = 1e-6 * (1.0 + at.len());
|
||||
(by.is_finite() && by.len() > tol).then(|| (name.clone(), by))
|
||||
})
|
||||
.collect();
|
||||
if !moves.is_empty() {
|
||||
let _ = d.modify_entity(h, |e| {
|
||||
for (name, by) in &moves {
|
||||
e.common.move_at(name, *by);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1024,6 +1024,11 @@ pub(crate) struct AnnoPayload {
|
||||
struct AnnoObject {
|
||||
handle: String,
|
||||
scales: Vec<cadcraft_doc::AnnoScale>,
|
||||
/// Where the object sits at a scale when it was moved there alone (see `Common::anno_moves`):
|
||||
/// a format without annotation scale contexts (or a DWG, whose bridge doesn't convert them
|
||||
/// yet) keeps them here.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
moves: Vec<cadcraft_doc::AnnoMove>,
|
||||
}
|
||||
|
||||
/// Most annotative objects read from one file.
|
||||
@@ -1041,7 +1046,7 @@ pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing, contexts: bool) -> Option<V
|
||||
.iter()
|
||||
.chain(d.layouts.iter().flat_map(|l| l.entities.iter()))
|
||||
.filter(|e| cadcraft_doc::is_annotative(e) && !(contexts && crate::dxf_anno::has_contexts(e)))
|
||||
.map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone() })
|
||||
.map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone(), moves: e.common.anno_moves.clone() })
|
||||
.collect();
|
||||
if cannoscale == "1:1" && annoallvisible == 1 && blocks.is_empty() && objects.is_empty() {
|
||||
return None;
|
||||
@@ -1102,9 +1107,18 @@ pub(crate) fn apply_anno(d: &mut cadcraft_doc::Drawing, p: AnnoPayload) {
|
||||
scales.push(s);
|
||||
}
|
||||
}
|
||||
// Each move once, for a scale the object keeps, by a finite offset.
|
||||
let mut moves: Vec<cadcraft_doc::AnnoMove> = Vec::new();
|
||||
for m in o.moves.into_iter().take(cadcraft_doc::MAX_SCALES) {
|
||||
let known = scales.iter().any(|s| s.name.eq_ignore_ascii_case(&m.scale));
|
||||
if known && m.by.is_finite() && !moves.iter().any(|x| x.scale.eq_ignore_ascii_case(&m.scale)) {
|
||||
moves.push(m);
|
||||
}
|
||||
}
|
||||
store.modify(h, |e| {
|
||||
if cadcraft_doc::can_be_annotative(&e.kind) {
|
||||
e.common.anno_scales = scales;
|
||||
e.common.anno_moves = moves;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
use super::{
|
||||
Block, Color, Common, Dimension, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext,
|
||||
};
|
||||
use super::{Block, Color, Common, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext};
|
||||
|
||||
/// What happens to the dimension blocks read from a file (#495): a dimension that still names
|
||||
/// its block is written with that block, under its name, and `*D` blocks nothing else
|
||||
@@ -79,81 +77,6 @@ pub(super) fn reuse_handles(ents: &mut [Entity], old: &Block, taken: &mut std::c
|
||||
}
|
||||
}
|
||||
|
||||
/// Anonymous dimension blocks (`*D1`…) with the rendered geometry, as consumers expect.
|
||||
pub(super) fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Vec<Entity> {
|
||||
// The dimension as drawn: its overrides, DIMSCALE (0 = the drawing's) and text font.
|
||||
let style = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
|
||||
let g = cadcraft_render::dimension_in(d, dm);
|
||||
let mut out = Vec::new();
|
||||
// Each part in its style colour (DIMCLRD, DIMCLRE, DIMCLRT), ByBlock when the style says so,
|
||||
// as AutoCAD writes them: readers that draw the block drew every part ByBlock, i.e. in the
|
||||
// dimension's own colour (#1052).
|
||||
let in_color = |color: Color| Common { layer: layer.into(), color, ..Common::default() };
|
||||
let (dim_c, ext_c, text_c) = (in_color(style.dim_line_color), in_color(style.ext_line_color), in_color(style.text_color));
|
||||
let line_entities = |i: usize, l: &[Vec2]| -> Vec<Entity> {
|
||||
let c = match g.line_roles.get(i) {
|
||||
Some(cadcraft_render::LineRole::Ext) => &ext_c,
|
||||
_ => &dim_c,
|
||||
};
|
||||
l.windows(2)
|
||||
.filter_map(|seg| match seg {
|
||||
[a, b] => Some(Entity { handle: Handle(0), common: c.clone(), kind: EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) }) }),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// The text's marks (arc length symbol, DIMINSPECT frame) go after the text background.
|
||||
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| !g.text_marks.contains(i)) {
|
||||
out.extend(line_entities(i, l));
|
||||
}
|
||||
for t in &g.fills {
|
||||
if let [a, b, cc] = t.as_slice() {
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: dim_c.clone(),
|
||||
kind: EntityKind::Solid(Solid { corners: [a.to3(0.0), b.to3(0.0), cc.to3(0.0), cc.to3(0.0)] }),
|
||||
});
|
||||
}
|
||||
}
|
||||
// DIMTFILL 2: the text background in DIMTFILLCLR, under the text and its marks (SOLID
|
||||
// corners go 1, 2, 4, 3).
|
||||
if style.text_fill == 2
|
||||
&& let [p0, p1, p2, p3] = g.text_fill.as_slice()
|
||||
{
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: in_color(style.text_fill_color),
|
||||
kind: EntityKind::Solid(Solid { corners: [p0.to3(0.0), p1.to3(0.0), p3.to3(0.0), p2.to3(0.0)] }),
|
||||
});
|
||||
}
|
||||
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| g.text_marks.contains(i)) {
|
||||
out.extend(line_entities(i, l));
|
||||
}
|
||||
// The text, and the part after `\X` below the dimension line as a second MTEXT, as AutoCAD
|
||||
// writes it (#1055).
|
||||
let texts = std::iter::once((g.value.clone(), g.text_pos)).chain(g.below.clone());
|
||||
for (contents, at) in texts.filter(|(t, _)| !t.is_empty()) {
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: text_c.clone(),
|
||||
kind: EntityKind::MText(MText {
|
||||
insert: at.to3(0.0),
|
||||
height: g.text_height,
|
||||
width: 0.0,
|
||||
attach: 5,
|
||||
rotation: g.text_angle,
|
||||
style: style.text_style.clone(),
|
||||
contents: cadcraft_render::DimGeometry::mtext_code(&contents),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Rows and columns written for a table (bounded like the renderer).
|
||||
pub(super) fn table_size(t: &Table) -> (usize, usize) {
|
||||
(t.row_heights.len().min(10_000), t.col_widths.len().min(10_000))
|
||||
|
||||
@@ -678,6 +678,7 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap
|
||||
let mut tags = cx.mleader_tags(d, m);
|
||||
if let Some(o) = cx.anno.objs.get(&e.handle) {
|
||||
crate::dxf_anno::mleader_at(&mut tags, crate::dxf_anno::default_factor(o));
|
||||
crate::dxf_anno::mleader_annotative(&mut tags);
|
||||
}
|
||||
w.t.extend(tags);
|
||||
cx.anno_xdata(w, e);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::assoc::std_assoc_refs;
|
||||
use super::blocks::{arrow_block_entities, dim_block_entities, dim_block_plan, reuse_handles, table_block_entities};
|
||||
use super::blocks::{arrow_block_entities, dim_block_plan, reuse_handles, table_block_entities};
|
||||
use super::common::annotative_xdata;
|
||||
use super::ctx::{AssocObj, Ctx};
|
||||
use super::entity::{entity, hatch_reactors};
|
||||
@@ -11,6 +11,7 @@ use super::{
|
||||
Space, TableStyle, Tag, Ucs, Vec2, Vec3, Version, W, dxf_ext,
|
||||
};
|
||||
use super::{entity_handles, structural_start};
|
||||
use cadcraft_render::dim_block_entities;
|
||||
|
||||
struct TableWritePlan<'a> {
|
||||
d: &'a Drawing,
|
||||
|
||||
@@ -798,3 +798,121 @@ fn the_current_scale_is_autocad_s_and_saving_keeps_it_current() {
|
||||
let var = recs.iter().find(|(k, _)| k == "DICTIONARYVAR").unwrap();
|
||||
assert_eq!(get(&var.1, 1), Some("1:1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_context_placing_the_object_elsewhere_reads_as_its_offset_there() {
|
||||
// The text sits 5 further right at 1:10 than its 1:2 position would put it.
|
||||
let src = FIXTURE.replacen("10 -40\n20 0\n11 30", "10 -35\n20 0\n11 35", 1);
|
||||
assert_ne!(src, FIXTURE);
|
||||
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
|
||||
let e = d.entity(Handle::parse_hex("30").unwrap()).unwrap();
|
||||
assert_eq!(e.common.anno_moves.len(), 1, "{:?}", e.common.anno_moves);
|
||||
assert_eq!(e.common.anno_moves[0].scale, "1:10");
|
||||
assert!(e.common.anno_moves[0].by.dist(cadcraft_geom::Vec2::new(5.0, 0.0)) < 1e-9);
|
||||
// An unmoved fixture has none.
|
||||
assert!(read().model.iter().all(|e| e.common.anno_moves.is_empty()));
|
||||
// Written back, the 1:10 context keeps its own position.
|
||||
let text = save(&d);
|
||||
let starts: Vec<f64> = contexts_of(&text, "30").iter().map(|c| num(&c.tags, 11)).collect();
|
||||
assert_eq!(starts, [30.0, 35.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offsets_made_in_cadcraft_survive_a_save() {
|
||||
let mut d = made();
|
||||
let hs: Vec<Handle> = d.model.iter().map(|e| e.handle).collect();
|
||||
for h in &hs {
|
||||
d.modify_entity(*h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(3.0, 4.0))).unwrap();
|
||||
}
|
||||
let back = cadcraft_io::read_dxf(save(&d).as_bytes()).unwrap();
|
||||
for h in &hs {
|
||||
let (a, b) = (d.entity(*h).unwrap(), back.entity(*h).unwrap());
|
||||
for f in [1.0, 50.0] {
|
||||
let shown = |d: &Drawing, e: &cadcraft_doc::Entity| match cadcraft_doc::anno_draw(e, f, true) {
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } => match cadcraft_doc::anno_placed(e, factor, by).kind {
|
||||
EntityKind::Text(t) => t.insert.xy(),
|
||||
EntityKind::Dimension(dm) if dm.user_text_pos => dm.text_mid.xy(),
|
||||
EntityKind::Dimension(dm) => cadcraft_render::dimension_in(d, &dm).text_pos,
|
||||
k => panic!("{k:?}"),
|
||||
},
|
||||
m => panic!("{m:?}"),
|
||||
};
|
||||
let (p, q) = (shown(&d, a), shown(&back, b));
|
||||
assert!(p.dist(q) < 1e-6, "{h:?} at {f}: {p:?} vs {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The landing and text of multileader `e` as it shows at annotation scale `f`.
|
||||
fn mleader_shown(e: &cadcraft_doc::Entity, f: f64) -> (cadcraft_geom::Vec2, cadcraft_geom::Vec2) {
|
||||
let cadcraft_doc::AnnoDraw::Scaled { factor, by } = cadcraft_doc::anno_draw(e, f, true) else { panic!("hidden") };
|
||||
let EntityKind::MLeader(m) = cadcraft_doc::anno_placed(e, factor, by).kind else { panic!("multileader") };
|
||||
(m.landing.xy(), m.text.unwrap().insert.xy())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multileader_moved_at_one_scale_keeps_it_through_dxf() {
|
||||
let (mut d, h) = with_mleader();
|
||||
d.modify_entity(h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(2.0, -1.0))).unwrap();
|
||||
let dxf_back = cadcraft_io::read_dxf(save(&d).as_bytes()).unwrap();
|
||||
let a = d.entity(h).unwrap();
|
||||
{
|
||||
let back = &dxf_back;
|
||||
let b = back.model.iter().find(|e| matches!(e.kind, EntityKind::MLeader(_))).unwrap();
|
||||
for f in [1.0, 10.0] {
|
||||
let ((la, ta), (lb, tb)) = (mleader_shown(a, f), mleader_shown(b, f));
|
||||
assert!(la.dist(lb) < 1e-6 && ta.dist(tb) < 1e-6, "at {f}: {la:?} {ta:?} vs {lb:?} {tb:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A multileader moved at one scale alone is there again after a DWG round trip, carried by
|
||||
/// CADCraft's own record (the DWG bridge doesn't convert contexts yet, storytold/craft-libs#2005).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_multileader_moved_at_one_scale_keeps_it_through_dwg() {
|
||||
cadcraft_io::dwg_worker::allow_in_process();
|
||||
let (mut d, h) = with_mleader();
|
||||
d.modify_entity(h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(2.0, -1.0))).unwrap();
|
||||
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
|
||||
let dwg_back = cadcraft_io::read(&dwg, "x.dwg").unwrap();
|
||||
let a = d.entity(h).unwrap();
|
||||
{
|
||||
let back = &dwg_back;
|
||||
let b = back.model.iter().find(|e| matches!(e.kind, EntityKind::MLeader(_))).unwrap();
|
||||
for f in [1.0, 10.0] {
|
||||
let ((la, ta), (lb, tb)) = (mleader_shown(a, f), mleader_shown(b, f));
|
||||
assert!(la.dist(lb) < 1e-6 && ta.dist(tb) < 1e-6, "at {f}: {la:?} {ta:?} vs {lb:?} {tb:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The MULTILEADER entity's own 293 ("enable annotation scale", after its `CONTEXT_DATA{` block).
|
||||
fn mleader_enable_annotation_scale(text: &str) -> Option<String> {
|
||||
let recs = records(text);
|
||||
let (_, t) = recs.iter().find(|(k, _)| k == "MULTILEADER")?;
|
||||
let close = t.iter().position(|(c, _)| *c == 301)?;
|
||||
t.iter().skip(close + 1).find(|(c, _)| *c == 293).map(|(_, v)| v.trim().to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_annotative_multileader_has_annotation_scale_enabled() {
|
||||
// AutoCAD's ANNORESET passes over a multileader whose 293 is off, even with its contexts.
|
||||
let (d, h) = with_mleader();
|
||||
assert_eq!(mleader_enable_annotation_scale(&save(&d)).as_deref(), Some("1"));
|
||||
let mut plain = d.clone();
|
||||
plain.modify_entity(h, |e| e.common.anno_scales.clear()).unwrap();
|
||||
assert_eq!(mleader_enable_annotation_scale(&save(&plain)).as_deref(), Some("0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_context_positions_do_not_panic() {
|
||||
for bad in ["10 1e309\n20 nan\n11 inf", "10 x\n20 0\n11 -1e308", "10 -40\n20 0\n11 1e308"] {
|
||||
let src = FIXTURE.replacen("10 -40\n20 0\n11 30", bad, 1);
|
||||
let Ok(d) = cadcraft_io::read_dxf(dxf(&src).as_bytes()) else { continue };
|
||||
for e in d.model.iter() {
|
||||
assert!(e.common.anno_moves.iter().all(|m| m.by.is_finite()), "{:?}", e.common.anno_moves);
|
||||
}
|
||||
let _ = save(&d);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,8 +204,21 @@ fn entity(expected: &Entity, actual: &Entity, context: &str) {
|
||||
|
||||
fn common(expected: &Common, actual: &Common, context: &str) {
|
||||
// No `..`: adding a field requires deciding its preservation contract here.
|
||||
let Common { layer, color, linetype, lineweight, ltscale, transparency, visible, thickness, extrusion, plot_style, anno_scales, xdata } =
|
||||
expected;
|
||||
let Common {
|
||||
layer,
|
||||
color,
|
||||
linetype,
|
||||
lineweight,
|
||||
ltscale,
|
||||
transparency,
|
||||
visible,
|
||||
thickness,
|
||||
extrusion,
|
||||
plot_style,
|
||||
anno_scales,
|
||||
anno_moves,
|
||||
xdata,
|
||||
} = expected;
|
||||
equal(layer, &actual.layer, context, "layer");
|
||||
equal(color, &actual.color, context, "color");
|
||||
equal(linetype, &actual.linetype, context, "linetype");
|
||||
@@ -217,6 +230,7 @@ fn common(expected: &Common, actual: &Common, context: &str) {
|
||||
equal(extrusion, &actual.extrusion, context, "extrusion");
|
||||
equal(plot_style, &actual.plot_style, context, "plot_style");
|
||||
equal(anno_scales, &actual.anno_scales, context, "anno_scales");
|
||||
equal(anno_moves, &actual.anno_moves, context, "anno_moves");
|
||||
equal(xdata, &actual.xdata, context, "xdata");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! The contents of a dimension's anonymous `*D` block: the dimension's graphics as plain objects.
|
||||
|
||||
use cadcraft_doc::{Common, Dimension, Line, MText, Solid};
|
||||
|
||||
use super::{Color, DimGeometry, Drawing, Entity, EntityKind, Handle, LineRole, Vec2, dimension_in};
|
||||
|
||||
/// Anonymous dimension blocks (`*D1`…) with the rendered geometry, as consumers expect.
|
||||
///
|
||||
/// The entities of the block of dimension `dm` on layer `layer`, with handle 0. The DXF/DWG
|
||||
/// writer makes the blocks of a saved file with it.
|
||||
pub fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Vec<Entity> {
|
||||
// The dimension as drawn: its overrides, DIMSCALE (0 = the drawing's) and text font.
|
||||
let style = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
|
||||
let g = dimension_in(d, dm);
|
||||
let mut out = Vec::new();
|
||||
// Each part in its style colour (DIMCLRD, DIMCLRE, DIMCLRT), ByBlock when the style says so,
|
||||
// as AutoCAD writes them: readers that draw the block drew every part ByBlock, i.e. in the
|
||||
// dimension's own colour (#1052).
|
||||
let in_color = |color: Color| Common { layer: layer.into(), color, ..Common::default() };
|
||||
let (dim_c, ext_c, text_c) = (in_color(style.dim_line_color), in_color(style.ext_line_color), in_color(style.text_color));
|
||||
let line_entities = |i: usize, l: &[Vec2]| -> Vec<Entity> {
|
||||
let c = match g.line_roles.get(i) {
|
||||
Some(LineRole::Ext) => &ext_c,
|
||||
_ => &dim_c,
|
||||
};
|
||||
l.windows(2)
|
||||
.filter_map(|seg| match seg {
|
||||
[a, b] => Some(Entity { handle: Handle(0), common: c.clone(), kind: EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) }) }),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// The text's marks (arc length symbol, DIMINSPECT frame) go after the text background.
|
||||
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| !g.text_marks.contains(i)) {
|
||||
out.extend(line_entities(i, l));
|
||||
}
|
||||
for t in &g.fills {
|
||||
if let [a, b, cc] = t.as_slice() {
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: dim_c.clone(),
|
||||
kind: EntityKind::Solid(Solid { corners: [a.to3(0.0), b.to3(0.0), cc.to3(0.0), cc.to3(0.0)] }),
|
||||
});
|
||||
}
|
||||
}
|
||||
// DIMTFILL 2: the text background in DIMTFILLCLR, under the text and its marks (SOLID
|
||||
// corners go 1, 2, 4, 3).
|
||||
if style.text_fill == 2
|
||||
&& let [p0, p1, p2, p3] = g.text_fill.as_slice()
|
||||
{
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: in_color(style.text_fill_color),
|
||||
kind: EntityKind::Solid(Solid { corners: [p0.to3(0.0), p1.to3(0.0), p3.to3(0.0), p2.to3(0.0)] }),
|
||||
});
|
||||
}
|
||||
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| g.text_marks.contains(i)) {
|
||||
out.extend(line_entities(i, l));
|
||||
}
|
||||
// The text, and the part after `\X` below the dimension line as a second MTEXT, as AutoCAD
|
||||
// writes it (#1055).
|
||||
let texts = std::iter::once((g.value.clone(), g.text_pos)).chain(g.below.clone());
|
||||
for (contents, at) in texts.filter(|(t, _)| !t.is_empty()) {
|
||||
out.push(Entity {
|
||||
handle: Handle(0),
|
||||
common: text_c.clone(),
|
||||
kind: EntityKind::MText(MText {
|
||||
insert: at.to3(0.0),
|
||||
height: g.text_height,
|
||||
width: 0.0,
|
||||
attach: 5,
|
||||
rotation: g.text_angle,
|
||||
style: style.text_style.clone(),
|
||||
contents: DimGeometry::mtext_code(&contents),
|
||||
line_spacing: 1.0,
|
||||
line_spacing_exact: false,
|
||||
columns: None,
|
||||
background: None,
|
||||
}),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -82,8 +82,8 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
|
||||
};
|
||||
match mode {
|
||||
cadcraft_doc::AnnoDraw::Hidden => return,
|
||||
cadcraft_doc::AnnoDraw::Scaled(f) => {
|
||||
let mut scaled = cadcraft_doc::anno_scaled(e, f);
|
||||
cadcraft_doc::AnnoDraw::Scaled { factor, by } => {
|
||||
let mut scaled = cadcraft_doc::anno_placed(e, factor, by);
|
||||
scaled.common.anno_scales.clear();
|
||||
return entity_parts(b, ctx, &scaled);
|
||||
}
|
||||
|
||||
@@ -590,6 +590,7 @@ pub use table::{
|
||||
};
|
||||
|
||||
mod blocks;
|
||||
mod dim_block;
|
||||
mod dim_draw;
|
||||
mod display;
|
||||
mod draw;
|
||||
@@ -598,6 +599,7 @@ mod props;
|
||||
mod text_entity;
|
||||
mod viewports;
|
||||
|
||||
pub use dim_block::dim_block_entities;
|
||||
pub use dim_draw::{dim_text, dimension_in};
|
||||
pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha};
|
||||
pub use pipeline::{Options, build, build_entities, build_entities_in_viewport, build_plot};
|
||||
|
||||
@@ -44,8 +44,8 @@ craft-update = { workspace = true, features = ["screen-testing"] }
|
||||
# The workspace `egui` dependency enables `default_fonts` and `monochrome_emoji_fonts` in
|
||||
# production too; the tests exercise the same installed chain as the app.
|
||||
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
|
||||
# Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) translation in tests (same naga wgpu uses).
|
||||
naga = { version = "30", features = ["wgsl-in", "glsl-out"] }
|
||||
# Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) and Metal translations in tests (same naga wgpu uses).
|
||||
naga = { version = "30", features = ["wgsl-in", "glsl-out", "msl-out"] }
|
||||
|
||||
[build-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -62,7 +62,7 @@ pub(super) fn draw_selection_grips(app: &mut CadApp, painter: &egui::Painter, xf
|
||||
if let Some(e) = st.doc.entity(*h)
|
||||
&& st.shows(e)
|
||||
{
|
||||
let grips = e.kind.grips();
|
||||
let grips = cadcraft_engine::grips::shown_grips(&st.doc, e, st.anno_view());
|
||||
let count = grips.len();
|
||||
for (gi, g) in grips.into_iter().enumerate() {
|
||||
let sp = xf.to_screen(g);
|
||||
@@ -182,7 +182,7 @@ pub(super) fn grip_at(app: &CadApp, xf: &Xf, hover: Option<Pos2>) -> Option<(Han
|
||||
if !st.shows(e) || st.doc.layer(&e.common.layer).is_some_and(|l| l.locked) {
|
||||
continue;
|
||||
}
|
||||
let grips = e.kind.grips();
|
||||
let grips = cadcraft_engine::grips::shown_grips(&st.doc, e, st.anno_view());
|
||||
let count = grips.len();
|
||||
for (i, g) in grips.into_iter().enumerate() {
|
||||
let sp = xf.to_screen(g);
|
||||
|
||||
@@ -44,13 +44,25 @@ const TOOLBAR: &[&[(Icon, &str, &str, Option<&str>)]] = &[
|
||||
/// Height of the macOS integrated title row (#161): the standard 28 pt title-bar band AppKit centres the traffic
|
||||
/// lights in.
|
||||
const MAC_TITLE_BAR: f32 = 28.0;
|
||||
/// Height of the framework's title bar where it carries the window buttons (GNOME on Wayland, [`crate::title_bar`]):
|
||||
/// the framework theme's `size.bar.title`.
|
||||
const INTEGRATED_TITLE_BAR: f32 = 38.0;
|
||||
/// The width of the toolbar's More button.
|
||||
const MORE_WIDTH: f32 = 30.0;
|
||||
|
||||
/// Title row (with the integrated macOS title bar) and the Tool Bar.
|
||||
/// Title row (with the integrated macOS title bar, or the framework's title bar with the window buttons where the
|
||||
/// desktop leaves the frame to the app) and the Tool Bar.
|
||||
pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get();
|
||||
let title_h = if app.integrated_titlebar { MAC_TITLE_BAR } else { 0.0 };
|
||||
let mac = ui.ctx().os().is_mac();
|
||||
// In full screen the framework's bar shows no window buttons, so the row goes too; the macOS row is unchanged.
|
||||
let fullscreen = ui.ctx().input(|i| i.viewport().fullscreen.unwrap_or(false));
|
||||
let title_h = match (app.integrated_titlebar, mac) {
|
||||
(false, _) => 0.0,
|
||||
(true, true) => MAC_TITLE_BAR,
|
||||
(true, false) if fullscreen => 0.0,
|
||||
(true, false) => INTEGRATED_TITLE_BAR,
|
||||
};
|
||||
let tb_h = if app.ui.show_toolbar { 34.0 } else { 0.0 };
|
||||
egui::Panel::top("cc_title_toolbar").exact_size(title_h + tb_h).frame(egui::Frame::NONE.fill(t.chrome)).show(ui, |ui| {
|
||||
let r = ui.max_rect();
|
||||
@@ -70,10 +82,9 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
if tb_h > 0.0 {
|
||||
let row = Rect::from_min_size(pos2(r.left(), r.top() + title_h), vec2(r.width(), tb_h));
|
||||
let mut x = r.left() + if app.integrated_titlebar { 120.0 } else { 12.0 };
|
||||
let mut x = r.left() + if app.integrated_titlebar && mac { 120.0 } else { 12.0 };
|
||||
let size = 26.0;
|
||||
let mut clicked = None;
|
||||
let mac = ui.ctx().os().is_mac();
|
||||
let widths: Vec<_> = TOOLBAR.iter().map(|group| group.len() as f32 * (size + 6.0) - 6.0).collect();
|
||||
let available = (row.right() - 12.0 - x).max(0.0);
|
||||
let items: Vec<_> = widths.iter().enumerate().map(|(i, w)| FitItem::new(*w, i as u16, FitKeep::Free)).collect();
|
||||
|
||||
@@ -1100,6 +1100,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The patched wgpu-hal (vendor/wgpu-hal, #1631) compiles with the newest Metal language the
|
||||
/// Mac's compiler accepts, which can be as old as macOS 11's (2.3, LSMinimumSystemVersion in
|
||||
/// packaging/macos/Info.plist.in), so the canvas shader must still translate at that version.
|
||||
#[test]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
fn shader_translates_for_the_oldest_metal_the_app_supports() {
|
||||
let module = naga::front::wgsl::parse_str(SHADER).unwrap();
|
||||
let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap();
|
||||
for (stage, entry) in
|
||||
[(naga::ShaderStage::Vertex, "vs_line"), (naga::ShaderStage::Vertex, "vs_quad"), (naga::ShaderStage::Fragment, "fs_main")]
|
||||
{
|
||||
let options = naga::back::msl::Options { lang_version: (2, 3), ..Default::default() };
|
||||
let pipeline = naga::back::msl::PipelineOptions { entry_point: Some((stage, entry.into())), ..Default::default() };
|
||||
let (out, _) = naga::back::msl::write_string(&module, &info, &options, &pipeline).unwrap();
|
||||
assert!(out.contains(entry), "{entry}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A wgpu bump leaves the `[patch.crates-io]` copy of wgpu-hal unused (Cargo only warns) and
|
||||
/// brings #1631 back: older Macs would ask the Metal compiler for a version it rejects again.
|
||||
/// See vendor/wgpu-hal/CADCRAFT.md.
|
||||
#[test]
|
||||
fn wgpu_hal_is_the_patched_copy() {
|
||||
let lock = include_str!("../../../Cargo.lock").replace("\r\n", "\n");
|
||||
let hal: Vec<&str> = lock.split("[[package]]").filter(|p| p.contains("\nname = \"wgpu-hal\"\n")).collect();
|
||||
assert!(!hal.is_empty() && hal.iter().all(|p| !p.contains("\nsource = ")), "wgpu-hal comes from a registry, not vendor/wgpu-hal");
|
||||
}
|
||||
|
||||
/// `prims` polylines of `points` points each (all over the same vertices).
|
||||
fn polylines(prims: usize, points: usize) -> DisplayList {
|
||||
let mut l = list();
|
||||
|
||||
@@ -1504,6 +1504,8 @@ menu View عرض
|
||||
This library has no drawings or blocks. لا تحتوي هذه المكتبة على رسومات أو كتل.
|
||||
Only the first {n} are shown. يتم عرض أول {n} فقط.
|
||||
The drawing changed. Close the window and open it again. تغيّر الرسم. أغلق النافذة وافتحها مرة أخرى.
|
||||
Use system title bar استخدام شريط عنوان النظام
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. يعرض شريط عنوان بسيطاً لأزرار النافذة فوق شريط CADCraft نفسه. لا يرسم GNOME أشرطة العناوين للتطبيقات، لذا لا يتبع هذا الشريط سمته.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools أدوات إضافية
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1336 and column 24.
|
@@ -1486,6 +1486,8 @@ menu Modify Izmijeni
|
||||
Ctrl+Enter to apply Ctrl+Enter to apply
|
||||
Edit Text Edit Text
|
||||
The drawing changed. Close the window and open it again. Crtež se promijenio. Zatvorite prozor i otvorite ga ponovo.
|
||||
Use system title bar Koristi sistemsku naslovnu traku
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Prikaži osnovnu naslovnu traku za dugmad prozora iznad CADCraftove vlastite. GNOME ne crta naslovne trake za aplikacije, pa ova ne prati njegovu temu.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools Dodatni alati
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1444 and column 24.
|
@@ -1471,6 +1471,8 @@ menu Modify Modifikace
|
||||
This drawing has no blocks. Tento výkres neobsahuje žádné bloky.
|
||||
This library has no drawings or blocks. Tato knihovna neobsahuje žádné výkresy ani bloky.
|
||||
Only the first {n} are shown. Zobrazuje se pouze prvních {n}.
|
||||
Use system title bar Použít systémové záhlaví okna
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Zobrazí nad záhlavím CADCraftu jednoduché záhlaví s tlačítky okna. GNOME aplikacím záhlaví nekreslí, takže toto nesleduje jeho motiv.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools Další nástroje
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1407 and column 24.
|
@@ -1085,6 +1085,8 @@
|
||||
Ctrl+Enter to apply Ctrl+Enter to apply
|
||||
Edit Text Edit Text
|
||||
The drawing changed. Close the window and open it again. Die Zeichnung hat sich geändert. Schließen Sie das Fenster und öffnen Sie es erneut.
|
||||
Use system title bar System-Titelleiste verwenden
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Eine einfache Titelleiste für die Fensterknöpfe über der von CADCraft anzeigen. GNOME zeichnet für Apps keine Titelleisten, daher folgt diese nicht seinem Design.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools Zusätzliche Werkzeuge
|
||||
|
||||
|
@@ -1423,6 +1423,8 @@ menu View Προβολή
|
||||
Ctrl+Enter to apply Ctrl+Enter to apply
|
||||
Edit Text Edit Text
|
||||
The drawing changed. Close the window and open it again. Το σχέδιο άλλαξε. Κλείστε το παράθυρο και ανοίξτε το ξανά.
|
||||
Use system title bar Χρήση της γραμμής τίτλου του συστήματος
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Εμφανίζει μια απλή γραμμή τίτλου με τα κουμπιά του παραθύρου πάνω από τη γραμμή του CADCraft. Το GNOME δεν σχεδιάζει γραμμές τίτλου για τις εφαρμογές, οπότε αυτή δεν ακολουθεί το θέμα του.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools Πρόσθετα εργαλεία
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 234 and column 24.
|
@@ -1303,6 +1303,8 @@
|
||||
Ctrl+Enter to apply Ctrl+Enter to apply
|
||||
Edit Text Edit Text
|
||||
The drawing changed. Close the window and open it again. El dibujo cambió. Cierre la ventana y ábrala de nuevo.
|
||||
Use system title bar Usar la barra de título del sistema
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Muestra una barra de título básica con los botones de la ventana encima de la de CADCraft. GNOME no dibuja barras de título para las aplicaciones, así que esta no sigue su tema.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools Herramientas adicionales
|
||||
|
||||
|
@@ -1065,6 +1065,8 @@
|
||||
Press the keys Appuyez sur les touches
|
||||
Back to CADCraft's shortcut Revenir au raccourci de CADCraft
|
||||
A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. Un raccourci que vous définissez l'emporte sur celui de CADCraft. Les modifications s'appliquent tout de suite et sont conservées.
|
||||
Use system title bar Utiliser la barre de titre du système
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Affiche une barre de titre simple avec les boutons de la fenêtre au-dessus de celle de CADCraft. GNOME ne dessine pas de barre de titre pour les applications, celle-ci ne suit donc pas son thème.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools Outils supplémentaires
|
||||
|
||||
|
@@ -1388,6 +1388,8 @@ menu View Nézet
|
||||
Ctrl+Enter to apply Ctrl+Enter to apply
|
||||
Edit Text Edit Text
|
||||
The drawing changed. Close the window and open it again. A rajz megváltozott. Zárja be az ablakot, és nyissa meg újra.
|
||||
Use system title bar A rendszer címsorának használata
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Egyszerű címsort jelenít meg az ablak gombjaival a CADCraft saját címsora fölött. A GNOME nem rajzol címsort az alkalmazásoknak, ezért ez nem követi a témáját.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools További eszközök
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 16 and column 72.
|
@@ -1434,6 +1434,8 @@ menu Modify Edita
|
||||
ENTER INVIO
|
||||
Shortcut Menu: always enabled Menu di scelta rapida: sempre attivo
|
||||
Shortcut Menu: enabled when command options are present Menu di scelta rapida: attivo se il comando ha opzioni
|
||||
Use system title bar Usa la barra del titolo di sistema
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Mostra una semplice barra del titolo con i pulsanti della finestra sopra quella di CADCraft. GNOME non disegna barre del titolo per le app, quindi questa non segue il suo tema.
|
||||
Check for updates when CADCraft starts Controlla gli aggiornamenti all'avvio di CADCraft
|
||||
Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks. Se disattivato, CADCraft non propone mai un aggiornamento da solo; Aiuto ▸ Verifica aggiornamenti… continua a controllare.
|
||||
|
||||
|
||||
|
@@ -1519,6 +1519,8 @@ menu View ხედი
|
||||
This drawing has no blocks. ამ ნახაზში ბლოკები არ არის.
|
||||
This library has no drawings or blocks. ამ ბიბლიოთეკაში ნახაზები ან ბლოკები არ არის.
|
||||
Only the first {n} are shown. ნაჩვენებია მხოლოდ პირველი {n}.
|
||||
Use system title bar სისტემის სათაურის ზოლის გამოყენება
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. ფანჯრის ღილაკებისთვის მარტივი სათაურის ზოლის ჩვენება CADCraft-ის საკუთარი ზოლის ზემოთ. GNOME აპებისთვის სათაურის ზოლებს არ ხატავს, ამიტომ ეს ზოლი მის თემას არ მიჰყვება.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools დამატებითი ხელსაწყოები
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 10 and column 14.
|
@@ -1287,6 +1287,8 @@ menu Modify 수정
|
||||
Ctrl+Enter to apply Ctrl+Enter to apply
|
||||
Edit Text Edit Text
|
||||
The drawing changed. Close the window and open it again. 도면이 변경되었습니다. 창을 닫고 다시 여십시오.
|
||||
Use system title bar 시스템 제목 표시줄 사용
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. CADCraft의 제목 표시줄 위에 창 단추가 있는 기본 제목 표시줄을 표시합니다. GNOME은 앱의 제목 표시줄을 그리지 않으므로 이 표시줄은 테마를 따르지 않습니다.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools 추가 도구
|
||||
|
||||
|
@@ -2170,6 +2170,8 @@ menu Dimension Wymiarowanie
|
||||
The current file doesn't look whole, so {name} stays as it is and the current file will be replaced. Bieżący plik wygląda na niekompletny, więc {name} pozostanie bez zmian, a bieżący plik zostanie zastąpiony.
|
||||
The current file is kept as {name} until the next save. Bieżący plik zostanie zachowany jako {name} do następnego zapisu.
|
||||
The drawing changed. Close the window and open it again. Rysunek został zmieniony. Zamknij okno i otwórz je ponownie.
|
||||
Use system title bar Użyj systemowego paska tytułu
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Pokaż prosty pasek tytułu z przyciskami okna nad własnym paskiem CADCraft. GNOME nie rysuje pasków tytułu dla aplikacji, więc ten nie korzysta z jego motywu.
|
||||
This format can't keep these objects yet: {objects}. Ten format nie potrafi jeszcze zachować tych obiektów: {objects}.
|
||||
Turn on time-sensitive right-click Włącz obsługę prawego przycisku zależną od czasu
|
||||
Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode. Po wyłączeniu tej opcji prawy przycisk podczas polecenia działa zgodnie z ustawieniami trybu polecenia w oknie Dostosowanie prawego przycisku myszy.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 832 and column 20.
|
@@ -1493,6 +1493,8 @@ menu View Exibir
|
||||
Ctrl+Enter to apply Ctrl+Enter to apply
|
||||
Edit Text Edit Text
|
||||
The drawing changed. Close the window and open it again. O desenho mudou. Feche a janela e abra-a novamente.
|
||||
Use system title bar Usar a barra de título do sistema
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Mostra uma barra de título simples com os botões da janela acima da do CADCraft. O GNOME não desenha barras de título para os aplicativos, então esta não segue o tema dele.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools Ferramentas adicionais
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1441 and column 24.
|
@@ -1060,6 +1060,8 @@
|
||||
Ctrl+Enter to apply Ctrl+Enter to apply
|
||||
Edit Text Edit Text
|
||||
The drawing changed. Close the window and open it again. Чертёж изменился. Закройте окно и откройте его снова.
|
||||
Use system title bar Использовать системный заголовок окна
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Показывает простой заголовок окна с кнопками над заголовком CADCraft. GNOME не рисует заголовки для приложений, поэтому этот не следует его теме.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools Дополнительные инструменты
|
||||
|
||||
|
@@ -1511,6 +1511,8 @@ menu Modify Ändra
|
||||
Ctrl+Enter to apply Ctrl+Enter to apply
|
||||
Edit Text Edit Text
|
||||
The drawing changed. Close the window and open it again. Ritningen har ändrats. Stäng fönstret och öppna det igen.
|
||||
Use system title bar Använd systemets namnlist
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Visar en enkel namnlist med fönsterknapparna ovanför CADCrafts egen. GNOME ritar inga namnlister åt appar, så den här följer inte dess tema.
|
||||
DView DView
|
||||
Keyboard Shortcuts... Kortkommandon...
|
||||
Multiple Insert Infoga flera
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1500 and column 24.
|
@@ -1391,6 +1391,8 @@ menu View Görünüm
|
||||
Ctrl+Enter to apply Ctrl+Enter to apply
|
||||
Edit Text Edit Text
|
||||
The drawing changed. Close the window and open it again. Çizim değişti. Pencereyi kapatıp yeniden açın.
|
||||
Use system title bar Sistem başlık çubuğunu kullan
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. CADCraft'ın başlık çubuğunun üstünde pencere düğmelerini içeren basit bir başlık çubuğu gösterir. GNOME uygulamalar için başlık çubuğu çizmediğinden bu çubuk onun temasına uymaz.
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools Ek Araçlar
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 11 and column 13.
|
@@ -1468,6 +1468,8 @@
|
||||
ENTER Клавіша Enter
|
||||
Shortcut Menu: always enabled Контекстне меню: завжди
|
||||
Shortcut Menu: enabled when command options are present Контекстне меню: коли команда має параметри
|
||||
Use system title bar Використовувати системний заголовок вікна
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Показує простий заголовок вікна з кнопками над заголовком CADCraft. GNOME не малює заголовки для застосунків, тому цей не відповідає його темі.
|
||||
Check for updates when CADCraft starts Перевіряти оновлення під час запуску CADCraft
|
||||
Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks. Якщо вимкнено, CADCraft ніколи сам не пропонує оновлення; Довідка ▸ Перевірити оновлення… усе одно перевіряє.
|
||||
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1404 and column 24.
|
@@ -1492,6 +1492,8 @@ menu Modify Hiệu chỉnh
|
||||
Ctrl+Enter to apply Ctrl+Enter để áp dụng
|
||||
Edit Text Sửa chữ
|
||||
The drawing changed. Close the window and open it again. Bản vẽ đã thay đổi. Đóng cửa sổ và mở lại.
|
||||
Use system title bar Dùng thanh tiêu đề của hệ thống
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Hiện một thanh tiêu đề đơn giản cho các nút cửa sổ phía trên thanh của CADCraft. GNOME không vẽ thanh tiêu đề cho ứng dụng, nên thanh này không theo chủ đề của nó.
|
||||
# Phase 1 of craft-i18n#401: the strings the translation_gaps report listed as missing for vi.
|
||||
# Dimension Style Manager (DIMSTYLE)
|
||||
<style overrides> <ghi đè kiểu>
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1445 and column 24.
|
@@ -1530,6 +1530,8 @@ menu View 视图
|
||||
Ctrl+Enter to apply Ctrl+Enter 应用
|
||||
Edit Text 编辑文字
|
||||
The drawing changed. Close the window and open it again. 图纸已切换。请关闭窗口后重新打开。
|
||||
Use system title bar 使用系统标题栏
|
||||
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. 在 CADCraft 自己的标题栏上方显示带窗口按钮的基本标题栏。GNOME 不为应用绘制标题栏,因此此标题栏不跟随其主题。
|
||||
|
||||
# ArtCraft feature naming
|
||||
Additional Tools 其他工具
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1486 and column 24.
|
@@ -74,11 +74,13 @@ pub mod quick;
|
||||
pub mod save_loss;
|
||||
pub mod shortcut_menus;
|
||||
pub mod theme;
|
||||
pub mod title_bar;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod updates_ui;
|
||||
pub mod viewcube;
|
||||
pub mod vpscale;
|
||||
pub mod wblock;
|
||||
mod window_edges;
|
||||
|
||||
pub mod exchange;
|
||||
mod file_provider_app;
|
||||
@@ -150,6 +152,10 @@ pub struct UiState {
|
||||
pub last_lisp_dir: Option<String>,
|
||||
/// The folder the Command Aliases dialog last imported a `.pgp` file from.
|
||||
pub last_pgp_dir: Option<String>,
|
||||
/// Options ▸ Display ▸ Use system title bar: where the desktop leaves the window frame to the app (GNOME on
|
||||
/// Wayland), keep the desktop's frame instead of the framework's title bar ([`title_bar`]). Kept in the desktop
|
||||
/// workspace file, which is read before the window opens.
|
||||
pub system_title_bar: bool,
|
||||
}
|
||||
|
||||
/// A DXF/DWG file version (2000 … 2018).
|
||||
@@ -230,6 +236,7 @@ impl Default for UiState {
|
||||
hatch_patterns: Default::default(),
|
||||
last_lisp_dir: None,
|
||||
last_pgp_dir: None,
|
||||
system_title_bar: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -323,6 +330,8 @@ pub struct CadApp {
|
||||
/// Drawings being read on worker threads ([`opening`]).
|
||||
pub opening: opening::Opening,
|
||||
pub integrated_titlebar: bool,
|
||||
/// Both frames of Use system title bar, where it applies ([`title_bar::TitleBar`]).
|
||||
title_bar: Option<title_bar::TitleBar>,
|
||||
control_rx: Option<Receiver<ControlRequest>>,
|
||||
/// Fresh surface and identity snapshot (see [`capture`]).
|
||||
pub(crate) capture_geometry: Option<capture::CaptureGeometry>,
|
||||
@@ -439,6 +448,7 @@ impl CadApp {
|
||||
status: None,
|
||||
opening: opening::Opening::default(),
|
||||
integrated_titlebar: false,
|
||||
title_bar: None,
|
||||
control_rx: None,
|
||||
capture_geometry: None,
|
||||
capture_epoch: 0,
|
||||
@@ -1293,6 +1303,7 @@ impl CadApp {
|
||||
self.sync_bars();
|
||||
control::begin_frame(ui.ctx());
|
||||
let t = theme::Tokens::get();
|
||||
self.follow_title_bar(ui.ctx());
|
||||
chrome::title_and_toolbar(self, ui);
|
||||
if self.ui.in_window_menu {
|
||||
menus::menu_bar(self, ui);
|
||||
@@ -1326,6 +1337,8 @@ impl CadApp {
|
||||
autosave::gpu_notice(self, ui.ctx());
|
||||
autosave::failure_notice(self, ui.ctx());
|
||||
self.run_framework_dialogs(ui);
|
||||
// Last, so the edges' resize cursors win over the drawing area's.
|
||||
window_edges::show(ui.ctx());
|
||||
self.frame_ms = now_ms() - t0;
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
//! | `rightClickDefault`, `rightClickEdit` | with the time-sensitive right-click off, a right-click with no command running and nothing (`Default`) or something (`Edit`) selected: `"menu"` (the shortcut menu, default) or `"repeat"` (the last command) |
|
||||
//! | `rightClickCommand` | a right-click while a command runs, with the time-sensitive right-click off: `"menu"` (default), `"enter"`, or `"menuWithOptions"` (the menu when the prompt has options, else Enter) |
|
||||
//! | `systemCursor` | keep the system cursor visible over the drawing area |
|
||||
//! | `systemTitleBar` | where the desktop leaves the window frame to the app (GNOME on Wayland), keep the desktop's frame instead of the framework's title bar with the window buttons |
|
||||
//! | `historyLines` | command-line history lines, 0–12 |
|
||||
//! | `modelBackground`, `paperBackground` | `"#rrggbb"`, or `null` for the default |
|
||||
//! | `selectionColor` | the colour selected objects are highlighted in: `"#rrggbb"`, or `null` for the theme's |
|
||||
@@ -230,6 +231,7 @@ struct UiChanges {
|
||||
language: Option<crate::i18n::Preference>,
|
||||
save_format: Option<crate::SaveFormat>,
|
||||
system_cursor: Option<bool>,
|
||||
system_title_bar: Option<bool>,
|
||||
history_lines: Option<usize>,
|
||||
model_background: Option<Option<Color32>>,
|
||||
paper_background: Option<Option<Color32>>,
|
||||
@@ -268,6 +270,7 @@ fn parse_ui(key: &str, v: &Value, c: &mut UiChanges) -> Result<bool, String> {
|
||||
}
|
||||
"saveFormat" => c.save_format = Some(crate::SaveFormat::parse(text()?).ok_or("saveFormat must be dxf or dwg")?),
|
||||
"systemCursor" => c.system_cursor = Some(v.as_bool().ok_or("systemCursor must be true or false")?),
|
||||
"systemTitleBar" => c.system_title_bar = Some(v.as_bool().ok_or("systemTitleBar must be true or false")?),
|
||||
"historyLines" => {
|
||||
let n = v.as_u64().filter(|n| *n <= crate::cmdline::MAX_LINES as u64).ok_or("historyLines must be a whole number from 0 to 12")?;
|
||||
c.history_lines = Some(n as usize);
|
||||
@@ -330,6 +333,7 @@ fn ui_json(app: &CadApp) -> Map<String, Value> {
|
||||
m.insert("interfaceLanguage".into(), json!(app.ui.interface_language.code()));
|
||||
m.insert("saveFormat".into(), json!(app.ui.save_format.as_str()));
|
||||
m.insert("systemCursor".into(), json!(app.ui.system_cursor));
|
||||
m.insert("systemTitleBar".into(), json!(app.ui.system_title_bar));
|
||||
m.insert("historyLines".into(), json!(app.ui.history_lines));
|
||||
m.insert("modelBackground".into(), color_json(o.model_background));
|
||||
m.insert("paperBackground".into(), color_json(o.paper_background));
|
||||
@@ -389,6 +393,9 @@ fn run_json(app: &mut CadApp, params: &Value) -> Result<Value, String> {
|
||||
if let Some(b) = ui.system_cursor {
|
||||
app.ui.system_cursor = b;
|
||||
}
|
||||
if let Some(b) = ui.system_title_bar {
|
||||
app.ui.system_title_bar = b;
|
||||
}
|
||||
if let Some(n) = ui.history_lines {
|
||||
app.ui.history_lines = n;
|
||||
}
|
||||
|
||||
@@ -212,6 +212,21 @@ fn display(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map<String, Value>) {
|
||||
changes.insert("systemCursor".into(), json!(system_cursor));
|
||||
}
|
||||
hint(ui, crate::tl!("Screen magnifiers, screen readers and recorders follow the system cursor."));
|
||||
// Only where the framework's title bar carries the window buttons (GNOME on Wayland); elsewhere
|
||||
// the desktop draws the frame. `CADCRAFT_TITLEBAR` overrides the setting, so it isn't offered then.
|
||||
if app.system_title_bar_applies() {
|
||||
ui.add_space(6.0);
|
||||
let mut system = app.ui.system_title_bar;
|
||||
if ui.checkbox(&mut system, crate::tl!("Use system title bar")).changed() {
|
||||
changes.insert("systemTitleBar".into(), json!(system));
|
||||
}
|
||||
hint(
|
||||
ui,
|
||||
crate::tl!(
|
||||
"Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme."
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Files tab: save format and default version, new-drawing units, autosave interval and autosave file location; edits accumulate in `changes`.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Boolean environment switches (`CADCRAFT_VSYNC`, `CADCRAFT_WAYLAND`, ...): one parser, so every
|
||||
//! Boolean environment switches (`CADCRAFT_VSYNC`, `CADCRAFT_X11`, ...): one parser, so every
|
||||
//! variable accepts the same spellings.
|
||||
|
||||
/// `1/on/true/yes` or `0/off/false/no`, case- and space-insensitive. Blank or unset is `Default`;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Options ▸ Display ▸ Use system title bar: where the desktop leaves the window frame to the app (GNOME on
|
||||
//! Wayland), the framework's title bar carries the window buttons, in the order of GNOME's `button-layout`; the
|
||||
//! setting gives the window the desktop's frame instead, at once. craft-window decides the frame
|
||||
//! (`policy::decide_for`), as on macOS ([`crate::framework::frame_decision`]).
|
||||
|
||||
use craft_host::target::Backend;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use craft_window::policy::{self, Decision, TitleBarPref};
|
||||
|
||||
use crate::CadApp;
|
||||
|
||||
/// The window's frame for each value of Use system title bar, both decided at start-up from the desktop as it was
|
||||
/// then, so the app's buttons come back in the desktop's `button-layout` order.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TitleBar {
|
||||
/// The frame with the setting off: the app's buttons.
|
||||
app: Decision,
|
||||
/// The frame with the setting on: the desktop's.
|
||||
system: Decision,
|
||||
/// The setting the window's frame follows now.
|
||||
applied: bool,
|
||||
}
|
||||
|
||||
impl TitleBar {
|
||||
/// The frames for both values of the setting, or `None` to leave the frame to the desktop, as before. Only where
|
||||
/// the desktop draws no frame (a Wayland compositor without server-side decorations: GNOME) or
|
||||
/// `CADCRAFT_TITLEBAR` asks: the policy would also draw the app's buttons on desktops that frame their windows
|
||||
/// (Windows, KDE), which is a decision for the whole suite rather than this setting.
|
||||
#[must_use]
|
||||
pub fn new(app: Decision, system: Decision, system_title_bar: bool) -> Option<Self> {
|
||||
let leaves_frame_to_app = app.desktop.ssd == Some(false);
|
||||
(leaves_frame_to_app || app.overridden.is_some()).then_some(Self { app, system, applied: system_title_bar })
|
||||
}
|
||||
|
||||
/// The frame the window opens with.
|
||||
#[must_use]
|
||||
pub fn decision(&self) -> &Decision {
|
||||
if self.applied { &self.system } else { &self.app }
|
||||
}
|
||||
|
||||
/// `Some(true)` when `CADCRAFT_TITLEBAR` forced the app's buttons, `Some(false)` the desktop's frame; the setting
|
||||
/// then changes nothing.
|
||||
fn forced(&self) -> Option<bool> {
|
||||
self.app.overridden
|
||||
}
|
||||
}
|
||||
|
||||
/// [`TitleBar::new`] for this desktop; `forced_x11` when the app opens its window through XWayland.
|
||||
#[must_use]
|
||||
pub fn decide(forced_x11: bool, system_title_bar: bool) -> Option<TitleBar> {
|
||||
let backend = if forced_x11 { Backend::X11 } else { Backend::from_env() };
|
||||
let decide = |pref| policy::decide_for(craft_window::Prefix::new("CADCRAFT"), backend, pref);
|
||||
TitleBar::new(decide(TitleBarPref::Integrated), decide(TitleBarPref::System), system_title_bar)
|
||||
}
|
||||
|
||||
impl CadApp {
|
||||
/// The window opened with `title_bar`'s frame ([`decide`]): Use system title bar now changes it, and the title
|
||||
/// row follows it.
|
||||
pub fn set_title_bar(&mut self, title_bar: TitleBar) {
|
||||
self.integrated_titlebar = crate::framework::draws_title_row(Some(title_bar.decision()));
|
||||
self.title_bar = Some(title_bar);
|
||||
}
|
||||
|
||||
/// Whether Use system title bar changes anything here: the framework decides the frame and `CADCRAFT_TITLEBAR`
|
||||
/// doesn't.
|
||||
pub(crate) fn system_title_bar_applies(&self) -> bool {
|
||||
self.title_bar.as_ref().is_some_and(|t| t.forced().is_none())
|
||||
}
|
||||
|
||||
/// Follow Use system title bar at once, before the title row is drawn: the window gets the setting's frame, and
|
||||
/// the title row shows or goes with the window buttons.
|
||||
pub(crate) fn follow_title_bar(&mut self, ctx: &egui::Context) {
|
||||
let system = self.ui.system_title_bar;
|
||||
let Some(t) = self.title_bar.as_mut().filter(|t| t.forced().is_none() && t.applied != system) else { return };
|
||||
t.applied = system;
|
||||
let decision = t.decision().clone();
|
||||
self.integrated_titlebar = crate::framework::draws_title_row(Some(&decision));
|
||||
WindowHost::of(ctx).set_root_frame(decision);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::TitleBar;
|
||||
use craft_host::target::Backend;
|
||||
use craft_window::policy::{self, TitleBarPref};
|
||||
|
||||
/// Both frames as GNOME on Wayland gives them: no server-side decorations and no override.
|
||||
fn gnome() -> (policy::Decision, policy::Decision) {
|
||||
let decide = |pref| {
|
||||
let mut d = policy::decide_for(craft_window::Prefix::new("CADCRAFT_TEST_UNSET"), Backend::Wayland, pref);
|
||||
d.desktop.ssd = Some(false);
|
||||
d.overridden = None;
|
||||
d
|
||||
};
|
||||
(decide(TitleBarPref::Integrated), decide(TitleBarPref::System))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_where_the_desktop_leaves_the_frame_to_the_app() {
|
||||
let (app, system) = gnome();
|
||||
assert!(TitleBar::new(app.clone(), system.clone(), false).is_some(), "GNOME on Wayland");
|
||||
let mut framed = app.clone();
|
||||
framed.desktop.ssd = Some(true);
|
||||
assert!(TitleBar::new(framed.clone(), system.clone(), false).is_none(), "KDE and Sway draw their own frames");
|
||||
framed.overridden = Some(true);
|
||||
assert!(TitleBar::new(framed, system, false).is_some(), "CADCRAFT_TITLEBAR=app asks anyway");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_setting_picks_the_frame_and_the_override_beats_it() {
|
||||
let (app, system) = gnome();
|
||||
let t = TitleBar::new(app.clone(), system.clone(), false).unwrap();
|
||||
assert_eq!(t.decision(), &app);
|
||||
assert_eq!(t.forced(), None);
|
||||
let t = TitleBar::new(app.clone(), system.clone(), true).unwrap();
|
||||
assert_eq!(t.decision(), &system, "Use system title bar on: the desktop's frame");
|
||||
let mut forced = app;
|
||||
forced.overridden = Some(true);
|
||||
assert_eq!(TitleBar::new(forced, system, true).unwrap().forced(), Some(true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Resize edges for the framework's integrated frame ([`crate::title_bar`]: GNOME on Wayland, where the desktop draws
|
||||
//! no frame). The framework gives the window buttons and the move band, but only a window built from its own shell
|
||||
//! gets its resize grips; CADCraft hosts its own egui UI, so thin zones along the window's edges start the desktop's
|
||||
//! resize here. The resize goes through the framework (`WindowAction::StartResize`), which gives the button release
|
||||
//! back after the desktop's grab.
|
||||
|
||||
use craft_ui::runtime::windows::{ResizeEdge, WindowAction, WindowHost};
|
||||
use craft_window::policy::Frame;
|
||||
use egui::{Color32, CursorIcon, Pos2, Rect, Sense, Stroke, Vec2, ViewportId};
|
||||
|
||||
/// How far into the window an edge resizes it.
|
||||
const EDGE: f32 = 5.0;
|
||||
/// How far along an edge a corner reaches, so corners are easy to hit.
|
||||
const CORNER: f32 = 16.0;
|
||||
|
||||
/// The resize zones of a window filling `rect`: edges `edge` deep, and each corner an L of two strips reaching
|
||||
/// `corner` along both edges (a square would reach into the content).
|
||||
fn zones(rect: Rect, edge: f32, corner: f32) -> Vec<(ResizeEdge, Rect)> {
|
||||
let (l, r, t, b) = (rect.left(), rect.right(), rect.top(), rect.bottom());
|
||||
// Never inverted, however small the window.
|
||||
let zone = |x0: f32, x1: f32, y0: f32, y1: f32| Rect::from_min_max(Pos2::new(x0, y0), Pos2::new(x1.max(x0), y1.max(y0)));
|
||||
vec![
|
||||
(ResizeEdge::TopLeft, zone(l, l + corner, t, t + edge)),
|
||||
(ResizeEdge::TopLeft, zone(l, l + edge, t + edge, t + corner)),
|
||||
(ResizeEdge::TopRight, zone(r - corner, r, t, t + edge)),
|
||||
(ResizeEdge::TopRight, zone(r - edge, r, t + edge, t + corner)),
|
||||
(ResizeEdge::BottomLeft, zone(l, l + corner, b - edge, b)),
|
||||
(ResizeEdge::BottomLeft, zone(l, l + edge, b - corner, b - edge)),
|
||||
(ResizeEdge::BottomRight, zone(r - corner, r, b - edge, b)),
|
||||
(ResizeEdge::BottomRight, zone(r - edge, r, b - corner, b - edge)),
|
||||
(ResizeEdge::Top, zone(l + corner, r - corner, t, t + edge)),
|
||||
(ResizeEdge::Bottom, zone(l + corner, r - corner, b - edge, b)),
|
||||
(ResizeEdge::Left, zone(l, l + edge, t + corner, b - corner)),
|
||||
(ResizeEdge::Right, zone(r - edge, r, t + corner, b - corner)),
|
||||
]
|
||||
}
|
||||
|
||||
fn cursor(edge: ResizeEdge) -> CursorIcon {
|
||||
match edge {
|
||||
ResizeEdge::Top => CursorIcon::ResizeNorth,
|
||||
ResizeEdge::Bottom => CursorIcon::ResizeSouth,
|
||||
ResizeEdge::Right => CursorIcon::ResizeEast,
|
||||
ResizeEdge::Left => CursorIcon::ResizeWest,
|
||||
ResizeEdge::TopRight => CursorIcon::ResizeNorthEast,
|
||||
ResizeEdge::BottomRight => CursorIcon::ResizeSouthEast,
|
||||
ResizeEdge::TopLeft => CursorIcon::ResizeNorthWest,
|
||||
ResizeEdge::BottomLeft => CursorIcon::ResizeSouthWest,
|
||||
_ => CursorIcon::Default,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resize zones along the root window's edges and a hairline border, while the framework's integrated frame is the
|
||||
/// window's and the window is neither maximized nor full screen. The zones sit above everything else (in the
|
||||
/// foreground order), so a press there resizes instead of reaching the panel or canvas under it.
|
||||
pub(crate) fn show(ctx: &egui::Context) {
|
||||
let host = WindowHost::of(ctx);
|
||||
if !matches!(host.frame(), Frame::Integrated(_)) {
|
||||
return;
|
||||
}
|
||||
let (maximized, fullscreen) = ctx.input(|i| (i.viewport().maximized.unwrap_or(false), i.viewport().fullscreen.unwrap_or(false)));
|
||||
if maximized || fullscreen {
|
||||
return;
|
||||
}
|
||||
let screen = ctx.content_rect();
|
||||
let dark = crate::theme::active() == egui::Theme::Dark;
|
||||
egui::Area::new(egui::Id::unique("cadcraft_window_edges")).order(egui::Order::Foreground).fixed_pos(screen.min).interactable(true).show(
|
||||
ctx,
|
||||
|ui| {
|
||||
ui.set_min_size(Vec2::ZERO);
|
||||
for (n, (edge, rect)) in zones(screen, EDGE, CORNER).into_iter().enumerate() {
|
||||
if rect.width() <= 0.0 || rect.height() <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let response = ui.interact(rect, ui.scope_id().with(("edge", n)), Sense::drag()).on_hover_cursor(cursor(edge));
|
||||
// Sensing only drags, a drag starts on the press itself.
|
||||
if response.drag_started() {
|
||||
host.act(ViewportId::ROOT, WindowAction::StartResize(edge));
|
||||
}
|
||||
}
|
||||
// Without the desktop's frame or shadow, a hairline keeps the window apart from what's behind it.
|
||||
ui.painter().rect_stroke(screen, 0.0, Stroke::new(1.0, Color32::from_black_alpha(if dark { 160 } else { 60 })), egui::StrokeKind::Inside);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ResizeEdge, zones};
|
||||
use egui::{Pos2, Rect};
|
||||
|
||||
#[test]
|
||||
fn resize_zones_line_the_edges_without_overlapping() {
|
||||
let window = Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0));
|
||||
let zones = zones(window, 5.0, 16.0);
|
||||
let at = |x: f32, y: f32| zones.iter().filter(|(_, r)| r.contains(Pos2::new(x, y))).map(|(e, _)| *e).collect::<Vec<_>>();
|
||||
assert_eq!(at(1.0, 1.0), [ResizeEdge::TopLeft]);
|
||||
assert_eq!(at(2.0, 12.0), [ResizeEdge::TopLeft]);
|
||||
assert_eq!(at(400.0, 2.0), [ResizeEdge::Top]);
|
||||
assert_eq!(at(799.0, 300.0), [ResizeEdge::Right]);
|
||||
assert_eq!(at(400.0, 599.0), [ResizeEdge::Bottom]);
|
||||
assert_eq!(at(1.0, 300.0), [ResizeEdge::Left]);
|
||||
assert_eq!(at(799.0, 599.0), [ResizeEdge::BottomRight]);
|
||||
assert!(at(400.0, 300.0).is_empty(), "the middle of the window is left alone");
|
||||
assert!(at(12.0, 12.0).is_empty(), "corners stay along the edges");
|
||||
// Strips meet without overlapping.
|
||||
for y in [0.5, 4.5, 5.5, 15.5, 16.5, 595.5] {
|
||||
for x in [0.5, 4.5, 5.5, 15.5, 16.5, 795.5, 799.5] {
|
||||
assert!(at(x, y).len() <= 1, "({x}, {y}): {:?}", at(x, y));
|
||||
}
|
||||
}
|
||||
// A window smaller than its corners gets empty (not inverted) edge zones.
|
||||
for (_, r) in super::zones(Rect::from_min_size(Pos2::ZERO, egui::vec2(20.0, 20.0)), 5.0, 16.0) {
|
||||
assert!(r.width() >= 0.0 && r.height() >= 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,8 @@ description: |-
|
||||
|
||||
# The binaries link only glibc and libgcc_s directly. Windowing (X11/Wayland, xkbcommon) and the
|
||||
# GPU (Vulkan, EGL/GL) are loaded at runtime, so they are dependencies/recommendations here
|
||||
# rather than ELF NEEDED entries.
|
||||
# rather than ELF NEEDED entries. On a Wayland desktop the app runs natively and needs X11 only
|
||||
# with CADCRAFT_X11=1 (see main.rs), so the X11 libraries are recommendations.
|
||||
overrides:
|
||||
deb:
|
||||
depends:
|
||||
@@ -36,6 +37,7 @@ overrides:
|
||||
- libwayland-client0
|
||||
- libx11-6
|
||||
- libx11-xcb1
|
||||
- libxkbcommon-x11-0
|
||||
- libxcursor1
|
||||
- libxi6
|
||||
- libxrandr2
|
||||
@@ -48,6 +50,8 @@ overrides:
|
||||
recommends:
|
||||
- libwayland-client
|
||||
- libX11
|
||||
- libX11-xcb
|
||||
- libxkbcommon-x11
|
||||
- libXcursor
|
||||
- libXi
|
||||
- libXrandr
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
sonar.projectKey=storytold_cadcraft
|
||||
sonar.organization=storytold
|
||||
sonar.coverage.exclusions=packaging/**
|
||||
# Third-party crates copied in unchanged (apart from their noted patch), not ours to analyse.
|
||||
sonar.exclusions=vendor/**
|
||||
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "40f4a34ebaf56f9a046231f54125ad046239d3f3"
|
||||
},
|
||||
"path_in_vcs": "wgpu-hal"
|
||||
}
|
||||
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
# wgpu-hal 30.0.1, patched for CADCraft
|
||||
|
||||
A copy of [`wgpu-hal` 30.0.1](https://crates.io/crates/wgpu-hal/30.0.1) (MIT OR Apache-2.0, see
|
||||
`LICENSE.*`), used through `[patch.crates-io]` in the workspace `Cargo.toml`. Every file is the
|
||||
published crate unchanged except `src/metal/adapter.rs` and this note.
|
||||
|
||||
## The change
|
||||
|
||||
`src/metal/adapter.rs`, `accepted_msl_version`: the Metal shading language version is no longer
|
||||
taken from the macOS version alone. A tiny kernel is compiled with each version up to the OS's,
|
||||
newest first, and the first one the system's Metal compiler accepts is used. If none is accepted,
|
||||
the OS's version is kept, as upstream does. The same patch is in storytold/craft-anything
|
||||
`vendor/wgpu-hal`.
|
||||
|
||||
## Why
|
||||
|
||||
On Macs with older GPUs running a newer macOS than Apple ships for them (OpenCore Legacy Patcher),
|
||||
macOS 15 makes wgpu ask for `-std=metal3.2` while the Metal compiler stops at 3.1 or earlier. Every
|
||||
shader fails, the device is lost and CADCraft exits before its window opens (storytold/cadcraft#1631;
|
||||
upstream gfx-rs/wgpu#10687, closed with no fix on trunk; open fix proposal gfx-rs/wgpu#10725).
|
||||
|
||||
## Removing it
|
||||
|
||||
Delete this directory and its `[patch.crates-io]` entry once a released wgpu picks a Metal version the
|
||||
compiler accepts. `wgpu_hal_is_the_patched_copy` (`crates/ui-egui/src/gpu.rs`) fails when a wgpu bump
|
||||
leaves this copy unused, so the patch can't be dropped by accident: either port the change to the new
|
||||
version or confirm upstream fixed it and remove the copy and the test together.
|
||||
Vendored
+542
@@ -0,0 +1,542 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2021"
|
||||
rust-version = "1.87"
|
||||
name = "wgpu-hal"
|
||||
version = "30.0.1"
|
||||
authors = ["gfx-rs developers"]
|
||||
build = "build.rs"
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Hardware abstraction layer for wgpu, the cross-platform, safe, pure-rust graphics API"
|
||||
homepage = "https://wgpu.rs/"
|
||||
readme = "README.md"
|
||||
keywords = ["graphics"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/gfx-rs/wgpu"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = [
|
||||
"metal",
|
||||
"vulkan",
|
||||
"gles",
|
||||
"renderdoc",
|
||||
]
|
||||
rustdoc-args = [
|
||||
"--cfg",
|
||||
"docsrs",
|
||||
]
|
||||
targets = [
|
||||
"x86_64-unknown-linux-gnu",
|
||||
"x86_64-apple-darwin",
|
||||
"x86_64-pc-windows-msvc",
|
||||
"wasm32-unknown-unknown",
|
||||
]
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
ignored = ["cfg_aliases"]
|
||||
|
||||
[features]
|
||||
device_lost_panic = []
|
||||
dx12 = [
|
||||
"dep:arrayvec",
|
||||
"dep:bit-set",
|
||||
"dep:bytemuck",
|
||||
"dep:gpu-allocator",
|
||||
"dep:libloading",
|
||||
"dep:once_cell",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:range-alloc",
|
||||
"dep:windows-core",
|
||||
"gpu-allocator/d3d12",
|
||||
"naga/hlsl-out",
|
||||
"once_cell/std",
|
||||
"windows/Win32_Devices_DeviceAndDriverInstallation",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Graphics_Direct3D_Dxc",
|
||||
"windows/Win32_Graphics_Direct3D_Fxc",
|
||||
"windows/Win32_Graphics_Direct3D",
|
||||
"windows/Win32_Graphics_Direct3D12",
|
||||
"windows/Win32_Graphics_DirectComposition",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Security",
|
||||
"windows/Win32_System_Diagnostics_Debug",
|
||||
"windows/Win32_System_Kernel",
|
||||
"windows/Win32_System_Performance",
|
||||
"windows/Win32_System_Threading",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
fragile-send-sync-non-atomic-wasm = ["wgpu-types/fragile-send-sync-non-atomic-wasm"]
|
||||
gles = [
|
||||
"dep:arrayvec",
|
||||
"dep:bytemuck",
|
||||
"dep:glow",
|
||||
"dep:glutin_wgl_sys",
|
||||
"dep:js-sys",
|
||||
"dep:khronos-egl",
|
||||
"dep:libloading",
|
||||
"dep:ndk-sys",
|
||||
"dep:objc2",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:wasm-bindgen",
|
||||
"dep:wayland-sys",
|
||||
"dep:web-sys",
|
||||
"dep:windows-result",
|
||||
"naga/glsl-out",
|
||||
"wgpu-types/web",
|
||||
"windows-result/std",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Graphics_OpenGL",
|
||||
"windows/Win32_System_LibraryLoader",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
internal_error_panic = []
|
||||
metal = [
|
||||
"naga/msl-out",
|
||||
"dep:arrayvec",
|
||||
"dep:block2",
|
||||
"dep:bytemuck",
|
||||
"dep:libloading",
|
||||
"dep:objc2",
|
||||
"dep:objc2-core-foundation",
|
||||
"dep:objc2-core-graphics",
|
||||
"dep:objc2-foundation",
|
||||
"dep:objc2-metal",
|
||||
"dep:objc2-quartz-core",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:smallvec",
|
||||
"dep:raw-window-metal",
|
||||
]
|
||||
portable-atomic = [
|
||||
"dep:portable-atomic",
|
||||
"dep:portable-atomic-util",
|
||||
]
|
||||
renderdoc = [
|
||||
"dep:libloading",
|
||||
"dep:renderdoc-sys",
|
||||
]
|
||||
static-dxc = ["dep:mach-dxcompiler-rs"]
|
||||
validation_canary = ["dep:parking_lot"]
|
||||
vulkan = [
|
||||
"naga/spv-out",
|
||||
"dep:android_system_properties",
|
||||
"dep:arrayvec",
|
||||
"dep:ash",
|
||||
"dep:bytemuck",
|
||||
"dep:libc",
|
||||
"dep:libloading",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:raw-window-metal",
|
||||
"dep:smallvec",
|
||||
"dep:windows",
|
||||
"gpu-allocator/vulkan",
|
||||
"windows/Win32",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Foundation",
|
||||
"windows/Win32_Graphics_Dxgi",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "wgpu_hal"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[example]]
|
||||
name = "halmark"
|
||||
path = "examples/halmark/main.rs"
|
||||
|
||||
[[example]]
|
||||
name = "raw-gles"
|
||||
path = "examples/raw-gles.rs"
|
||||
required-features = ["gles"]
|
||||
|
||||
[[example]]
|
||||
name = "ray-traced-triangle"
|
||||
path = "examples/ray-traced-triangle/main.rs"
|
||||
|
||||
[dependencies.arrayvec]
|
||||
version = "0.7.1"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.bitflags]
|
||||
version = "2.9"
|
||||
|
||||
[dependencies.bytemuck]
|
||||
version = "1.22"
|
||||
features = [
|
||||
"extern_crate_alloc",
|
||||
"min_const_generics",
|
||||
"derive",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[dependencies.cfg-if]
|
||||
version = "1"
|
||||
|
||||
[dependencies.glow]
|
||||
version = "0.17"
|
||||
optional = true
|
||||
|
||||
[dependencies.hashbrown]
|
||||
version = "0.17"
|
||||
features = [
|
||||
"default-hasher",
|
||||
"inline-more",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[dependencies.log]
|
||||
version = "0.4.29"
|
||||
|
||||
[dependencies.naga]
|
||||
version = "30.0.0"
|
||||
|
||||
[dependencies.naga-types]
|
||||
version = "30.0.0"
|
||||
|
||||
[dependencies.ordered-float]
|
||||
version = ">=3, <6.0"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.parking_lot]
|
||||
version = "0.12.3"
|
||||
optional = true
|
||||
|
||||
[dependencies.profiling]
|
||||
version = "1.0.1"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.raw-window-handle]
|
||||
version = "0.6.2"
|
||||
default-features = false
|
||||
|
||||
[dependencies.static_assertions]
|
||||
version = "1.1"
|
||||
|
||||
[dependencies.thiserror]
|
||||
version = "2.0.12"
|
||||
default-features = false
|
||||
|
||||
[dependencies.wgpu-naga-bridge]
|
||||
version = "30.0.0"
|
||||
|
||||
[dependencies.wgpu-types]
|
||||
version = "30.0.0"
|
||||
default-features = false
|
||||
|
||||
[dev-dependencies.env_logger]
|
||||
version = "0.11"
|
||||
default-features = false
|
||||
|
||||
[dev-dependencies.glam]
|
||||
version = "0.33.0"
|
||||
|
||||
[dev-dependencies.naga]
|
||||
version = "30.0.0"
|
||||
features = [
|
||||
"wgsl-in",
|
||||
"termcolor",
|
||||
]
|
||||
|
||||
[dev-dependencies.winit]
|
||||
version = "0.30.8"
|
||||
features = ["android-native-activity"]
|
||||
|
||||
[build-dependencies.cfg_aliases]
|
||||
version = "0.2.2"
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.js-sys]
|
||||
version = "0.3.104"
|
||||
optional = true
|
||||
default-features = true
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.wasm-bindgen]
|
||||
version = "0.2.127"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.web-sys]
|
||||
version = "0.3.104"
|
||||
features = [
|
||||
"default",
|
||||
"Window",
|
||||
"HtmlCanvasElement",
|
||||
"WebGl2RenderingContext",
|
||||
"OffscreenCanvas",
|
||||
"VideoFrame",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))'.dependencies.drm]
|
||||
version = "0.15"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(all(windows, not(target_arch = "aarch64"), target_env = "msvc"))'.dependencies.mach-dxcompiler-rs]
|
||||
version = "0.1.4"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(any(not(target_has_atomic = "64"), not(target_has_atomic = "ptr")))'.dependencies.portable-atomic]
|
||||
version = "1.10"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies.glutin]
|
||||
version = "0.32"
|
||||
features = [
|
||||
"egl",
|
||||
"wgl",
|
||||
"wayland",
|
||||
"x11",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies.glutin-winit]
|
||||
version = "0.5"
|
||||
features = [
|
||||
"egl",
|
||||
"wgl",
|
||||
"wayland",
|
||||
"x11",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.ash]
|
||||
version = "0.38"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.gpu-allocator]
|
||||
version = "0.28"
|
||||
features = ["hashbrown"]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.khronos-egl]
|
||||
version = "6"
|
||||
features = ["dynamic"]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.libloading]
|
||||
version = "0.8"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.renderdoc-sys]
|
||||
version = "1"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.smallvec]
|
||||
version = "1.14"
|
||||
features = ["union"]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_has_atomic = "ptr"))'.dependencies.portable-atomic-util]
|
||||
version = "0.2.4"
|
||||
features = ["alloc"]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies.android_system_properties]
|
||||
version = "0.1.1"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies.ndk-sys]
|
||||
version = "0.6"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "emscripten")'.dependencies.khronos-egl]
|
||||
version = "6"
|
||||
features = [
|
||||
"static",
|
||||
"no-pkg-config",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "emscripten")'.dependencies.libloading]
|
||||
version = "0.8"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.block2]
|
||||
version = "0.6.2"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.bytemuck]
|
||||
version = "1.22"
|
||||
features = [
|
||||
"extern_crate_alloc",
|
||||
"min_const_generics",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2]
|
||||
version = "0.6.3"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-foundation]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"CFCGTypes",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-graphics]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"CGColorSpace",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-foundation]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"NSError",
|
||||
"NSProcessInfo",
|
||||
"NSRange",
|
||||
"NSString",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-metal]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"block2",
|
||||
"MTLAllocation",
|
||||
"MTLBlitCommandEncoder",
|
||||
"MTLBlitPass",
|
||||
"MTLBuffer",
|
||||
"MTLCaptureManager",
|
||||
"MTLCaptureScope",
|
||||
"MTLCommandBuffer",
|
||||
"MTLCommandEncoder",
|
||||
"MTLCommandQueue",
|
||||
"MTLComputeCommandEncoder",
|
||||
"MTLComputePass",
|
||||
"MTLComputePipeline",
|
||||
"MTLCounters",
|
||||
"MTLDepthStencil",
|
||||
"MTLDevice",
|
||||
"MTLDrawable",
|
||||
"MTLEvent",
|
||||
"MTLLibrary",
|
||||
"MTLPipeline",
|
||||
"MTLPixelFormat",
|
||||
"MTLRenderCommandEncoder",
|
||||
"MTLRenderPass",
|
||||
"MTLRenderPipeline",
|
||||
"MTLResource",
|
||||
"MTLSampler",
|
||||
"MTLStageInputOutputDescriptor",
|
||||
"MTLTexture",
|
||||
"MTLTypes",
|
||||
"MTLVertexDescriptor",
|
||||
"MTLAccelerationStructure",
|
||||
"MTLAccelerationStructureTypes",
|
||||
"MTLAccelerationStructureCommandEncoder",
|
||||
"MTLResidencySet",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-quartz-core]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"CALayer",
|
||||
"CAMetalLayer",
|
||||
"objc2-metal",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.raw-window-metal]
|
||||
version = "1.0"
|
||||
optional = true
|
||||
|
||||
[target."cfg(unix)".dependencies.libc]
|
||||
version = "0.2.183"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(unix)".dependencies.wayland-sys]
|
||||
version = "0.31.3"
|
||||
features = [
|
||||
"client",
|
||||
"dlopen",
|
||||
"egl",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[target."cfg(windows)".dependencies.bit-set]
|
||||
version = "0.10"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.glutin_wgl_sys]
|
||||
version = "0.6"
|
||||
optional = true
|
||||
|
||||
[target."cfg(windows)".dependencies.once_cell]
|
||||
version = "1.21"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.range-alloc]
|
||||
version = "0.1"
|
||||
optional = true
|
||||
|
||||
[target."cfg(windows)".dependencies.windows]
|
||||
version = "0.62"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.windows-core]
|
||||
version = "0.62"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.windows-result]
|
||||
version = "0.4"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[lints.rust]
|
||||
missing_debug_implementations = "warn"
|
||||
|
||||
[lints.rust.unexpected_cfgs]
|
||||
level = "warn"
|
||||
priority = 0
|
||||
check-cfg = [
|
||||
'cfg(feature, values("cargo-clippy"))',
|
||||
"cfg(web_sys_unstable_apis)",
|
||||
]
|
||||
+365
@@ -0,0 +1,365 @@
|
||||
[package]
|
||||
name = "wgpu-hal"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
description = "Hardware abstraction layer for wgpu, the cross-platform, safe, pure-rust graphics API"
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
keywords.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
# Override the workspace's `rust-version` key. `wgpu-core` and its dependencies
|
||||
# have a less strict MSRV, to allow firefox more leeway in updating their Rust toolchain.
|
||||
#
|
||||
# See the repo README for more information on MSRV policy.
|
||||
rust-version = "1.87"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
# Ideally we would enable all the features.
|
||||
#
|
||||
# However, the dx12 features fail to be documented because the docs.rs runner cross-compiling under
|
||||
# x86_64-unknown-linux-gnu cannot compile in that environment at the moment.
|
||||
features = ["metal", "vulkan", "gles", "renderdoc"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
targets = [
|
||||
"x86_64-unknown-linux-gnu",
|
||||
"x86_64-apple-darwin",
|
||||
"x86_64-pc-windows-msvc",
|
||||
"wasm32-unknown-unknown",
|
||||
]
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
# Cargo machete can't check build.rs dependencies. See https://github.com/bnjbvr/cargo-machete/issues/100
|
||||
ignored = ["cfg_aliases"]
|
||||
|
||||
[lints.rust]
|
||||
missing_debug_implementations = "warn"
|
||||
unexpected_cfgs = { level = "warn", check-cfg = [
|
||||
'cfg(feature, values("cargo-clippy"))', # objc's `msg_send` macro injects this in our code https://github.com/SSheldon/rust-objc/issues/125
|
||||
'cfg(web_sys_unstable_apis)', # web-sys uses this
|
||||
] }
|
||||
|
||||
[lib]
|
||||
|
||||
[features]
|
||||
########################
|
||||
### Backend Features ###
|
||||
########################
|
||||
|
||||
# The interaction of features between wgpu-core and wgpu-hal is a bit nuanced to get
|
||||
# the desired behavior on all platforms.
|
||||
#
|
||||
# At the wgpu-hal level the features are defined to enable the backends on all platforms
|
||||
# that can compile the backend. Vulkan for example will have an effect on Windows, Mac, Linux, and Android.
|
||||
# This is done with target conditional dependencies in wgpu-hal. This allows `--all-features`
|
||||
# to compile on all platforms.
|
||||
#
|
||||
# wgpu-core's features are defined to enable the backends on their "default" platforms. For example we
|
||||
# exclude the Vulkan backend on MacOS unless a separate feature `vulkan-portability` is enabled. In response
|
||||
# to these features, it enables features of platform specific crates. For example, the `vulkan` feature in wgpu-core
|
||||
# enables the `vulkan` feature in `wgpu-core-deps-windows-linux-android` which in turn enables the
|
||||
# `vulkan` feature in `wgpu-hal` _only_ on those platforms. If you enable the `vulkan-portability` feature, it
|
||||
# will enable the `vulkan` feature in `wgpu-core-deps-apple`. The only way to do this is unfortunately to have
|
||||
# a separate crate for each platform category that participates in the feature unification.
|
||||
#
|
||||
# This trick doesn't work at the `wgpu` level, because the `wgpu` -> `wgpu-core` dependency is conditional,
|
||||
# making the Cargo.toml signifigantly more complicated in all areas.
|
||||
#
|
||||
# See https://github.com/gfx-rs/wgpu/issues/3514, https://github.com/gfx-rs/wgpu/pull/7076,
|
||||
# and https://github.com/rust-lang/cargo/issues/1197 for more information.
|
||||
|
||||
## Enables the Metal backend when targeting Apple platforms.
|
||||
metal = [
|
||||
# Metal is only available on Apple platforms, therefore request MSL output also only if we target an Apple platform.
|
||||
"naga/msl-out",
|
||||
"dep:arrayvec",
|
||||
"dep:block2",
|
||||
"dep:bytemuck",
|
||||
"dep:libloading",
|
||||
"dep:objc2",
|
||||
"dep:objc2-core-foundation",
|
||||
"dep:objc2-core-graphics",
|
||||
"dep:objc2-foundation",
|
||||
"dep:objc2-metal",
|
||||
"dep:objc2-quartz-core",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:smallvec",
|
||||
"dep:raw-window-metal",
|
||||
]
|
||||
vulkan = [
|
||||
"naga/spv-out",
|
||||
"dep:android_system_properties",
|
||||
"dep:arrayvec",
|
||||
"dep:ash",
|
||||
"dep:bytemuck",
|
||||
"dep:libc",
|
||||
"dep:libloading",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:raw-window-metal",
|
||||
"dep:smallvec",
|
||||
"dep:windows",
|
||||
"gpu-allocator/vulkan",
|
||||
"windows/Win32",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Foundation",
|
||||
"windows/Win32_Graphics_Dxgi",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
]
|
||||
gles = [
|
||||
"dep:arrayvec",
|
||||
"dep:bytemuck",
|
||||
"dep:glow",
|
||||
"dep:glutin_wgl_sys",
|
||||
"dep:js-sys",
|
||||
"dep:khronos-egl",
|
||||
"dep:libloading",
|
||||
"dep:ndk-sys",
|
||||
"dep:objc2",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:wasm-bindgen",
|
||||
"dep:wayland-sys",
|
||||
"dep:web-sys",
|
||||
"dep:windows-result",
|
||||
"naga/glsl-out",
|
||||
"wgpu-types/web",
|
||||
"windows-result/std", # Need to enable this for the `Error` impl on `windows_result::Error` to work.
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Graphics_OpenGL",
|
||||
"windows/Win32_System_LibraryLoader",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
## Enables the DX12 backend when targeting Windows.
|
||||
dx12 = [
|
||||
"dep:arrayvec",
|
||||
"dep:bit-set",
|
||||
"dep:bytemuck",
|
||||
"dep:gpu-allocator",
|
||||
"dep:libloading",
|
||||
"dep:once_cell",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:range-alloc",
|
||||
"dep:windows-core",
|
||||
"gpu-allocator/d3d12",
|
||||
"naga/hlsl-out",
|
||||
"once_cell/std",
|
||||
"windows/Win32_Devices_DeviceAndDriverInstallation",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Graphics_Direct3D_Dxc",
|
||||
"windows/Win32_Graphics_Direct3D_Fxc",
|
||||
"windows/Win32_Graphics_Direct3D",
|
||||
"windows/Win32_Graphics_Direct3D12",
|
||||
"windows/Win32_Graphics_DirectComposition",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Security",
|
||||
"windows/Win32_System_Diagnostics_Debug",
|
||||
"windows/Win32_System_Kernel",
|
||||
"windows/Win32_System_Performance",
|
||||
"windows/Win32_System_Threading",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
|
||||
###########################
|
||||
### Misc Other Features ###
|
||||
###########################
|
||||
|
||||
static-dxc = ["dep:mach-dxcompiler-rs"]
|
||||
renderdoc = ["dep:libloading", "dep:renderdoc-sys"]
|
||||
fragile-send-sync-non-atomic-wasm = [
|
||||
"wgpu-types/fragile-send-sync-non-atomic-wasm",
|
||||
]
|
||||
portable-atomic = ["dep:portable-atomic", "dep:portable-atomic-util"]
|
||||
|
||||
###################################
|
||||
### Internal Debugging Features ###
|
||||
###################################
|
||||
|
||||
# Panic when running into a device lost error (for debugging purposes).
|
||||
# Only affects the d3d12 and vulkan backends.
|
||||
device_lost_panic = []
|
||||
# Panic when running into an internal error other than out-of-memory and device lost
|
||||
# (for debugging purposes).
|
||||
#
|
||||
# Only affects the d3d12 and vulkan backends.
|
||||
internal_error_panic = []
|
||||
# Tracks validation errors in a `VALIDATION_CANARY` static.
|
||||
validation_canary = ["dep:parking_lot"]
|
||||
|
||||
[[example]]
|
||||
name = "halmark"
|
||||
|
||||
[[example]]
|
||||
name = "raw-gles"
|
||||
required-features = ["gles"]
|
||||
|
||||
#####################
|
||||
### Platform: All ###
|
||||
#####################
|
||||
|
||||
[dependencies]
|
||||
naga.workspace = true
|
||||
wgpu-naga-bridge.workspace = true
|
||||
naga-types = { workspace = true }
|
||||
wgpu-types = { workspace = true, default-features = false }
|
||||
|
||||
# Dependencies in the lib and empty backend
|
||||
bitflags.workspace = true
|
||||
cfg-if.workspace = true
|
||||
log = { workspace = true }
|
||||
parking_lot = { workspace = true, optional = true }
|
||||
raw-window-handle.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
# Target agnostic dependencies used only in backends.
|
||||
arrayvec = { workspace = true, optional = true }
|
||||
bytemuck = { workspace = true, optional = true, features = ["derive"] }
|
||||
hashbrown = { workspace = true }
|
||||
ordered-float = { workspace = true, optional = true }
|
||||
profiling = { workspace = true, optional = true, default-features = false }
|
||||
static_assertions = { workspace = true }
|
||||
|
||||
# Backend: GLES
|
||||
glow = { workspace = true, optional = true }
|
||||
|
||||
########################
|
||||
### Platform: Native ###
|
||||
########################
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Backend: Vulkan and Dx12
|
||||
gpu-allocator = { workspace = true, optional = true }
|
||||
# Backend: Vulkan
|
||||
ash = { workspace = true, optional = true }
|
||||
smallvec = { workspace = true, optional = true, features = ["union"] }
|
||||
# Backend: GLES
|
||||
khronos-egl = { workspace = true, features = ["dynamic"], optional = true }
|
||||
libloading = { workspace = true, optional = true }
|
||||
renderdoc-sys = { workspace = true, optional = true }
|
||||
|
||||
##########################
|
||||
### Platform: All Unix ###
|
||||
##########################
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
# Backend: Vulkan
|
||||
libc = { workspace = true, optional = true }
|
||||
# backend: GLES
|
||||
wayland-sys = { version = "0.31.3", features = [
|
||||
"client",
|
||||
"dlopen",
|
||||
"egl",
|
||||
], optional = true }
|
||||
|
||||
## Support creating textures from DRM display/window handles.
|
||||
[target.'cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))'.dependencies]
|
||||
drm = { version = "0.15", optional = true }
|
||||
|
||||
#########################
|
||||
### Platform: Windows ###
|
||||
#########################
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# Backend: Dx12 and GLES
|
||||
windows = { workspace = true, optional = true }
|
||||
windows-core = { workspace = true, optional = true }
|
||||
windows-result = { workspace = true, optional = true }
|
||||
# Backend: Dx12
|
||||
bit-set = { workspace = true, optional = true }
|
||||
range-alloc = { workspace = true, optional = true }
|
||||
once_cell = { workspace = true, optional = true }
|
||||
# backend: GLES
|
||||
glutin_wgl_sys = { workspace = true, optional = true }
|
||||
|
||||
### Platform: x86/x86_64 Windows ###
|
||||
# This doesn't support aarch64. See https://github.com/gfx-rs/wgpu/issues/6860.
|
||||
# This doesn't support x86_64-pc-windows-gnu. See https://github.com/gfx-rs/wgpu/issues/8303
|
||||
#
|
||||
# ⚠️ Keep in sync with static_dxc cfg in build.rs and cfg_alias in `wgpu` crate ⚠️
|
||||
[target.'cfg(all(windows, not(target_arch = "aarch64"), target_env = "msvc"))'.dependencies]
|
||||
mach-dxcompiler-rs = { workspace = true, optional = true }
|
||||
|
||||
#######################
|
||||
### Platform: Apple ###
|
||||
#######################
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||
# Backend: Metal
|
||||
block2 = { workspace = true, optional = true }
|
||||
bytemuck = { workspace = true, optional = true }
|
||||
objc2 = { workspace = true, optional = true }
|
||||
objc2-core-foundation = { workspace = true, optional = true }
|
||||
objc2-core-graphics = { workspace = true, optional = true }
|
||||
objc2-foundation = { workspace = true, optional = true }
|
||||
objc2-metal = { workspace = true, optional = true }
|
||||
objc2-quartz-core = { workspace = true, optional = true }
|
||||
|
||||
# backend: Metal + Vulkan
|
||||
raw-window-metal = { workspace = true, optional = true }
|
||||
|
||||
#########################
|
||||
### Platform: Android ###
|
||||
#########################
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
android_system_properties = { workspace = true, optional = true }
|
||||
ndk-sys = { workspace = true, optional = true }
|
||||
|
||||
#############################
|
||||
### Platform: Webassembly ###
|
||||
#############################
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies]
|
||||
# Backend: GLES
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
web-sys = { workspace = true, optional = true, features = [
|
||||
"default",
|
||||
"Window",
|
||||
"HtmlCanvasElement",
|
||||
"WebGl2RenderingContext",
|
||||
"OffscreenCanvas",
|
||||
"VideoFrame",
|
||||
] }
|
||||
js-sys = { workspace = true, optional = true, default-features = true }
|
||||
|
||||
############################
|
||||
### Platform: Emscripten ###
|
||||
############################
|
||||
|
||||
[target.'cfg(target_os = "emscripten")'.dependencies]
|
||||
# Backend: GLES
|
||||
khronos-egl = { workspace = true, optional = true, features = [
|
||||
"static",
|
||||
"no-pkg-config",
|
||||
] }
|
||||
# Note: it's unused by emscripten, but we keep it to have single code base in egl.rs
|
||||
libloading = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(any(not(target_has_atomic = "64"), not(target_has_atomic = "ptr")))'.dependencies]
|
||||
portable-atomic = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(not(target_has_atomic = "ptr"))'.dependencies]
|
||||
portable-atomic-util = { workspace = true, features = [
|
||||
"alloc",
|
||||
], optional = true }
|
||||
|
||||
[build-dependencies]
|
||||
cfg_aliases.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger.workspace = true
|
||||
glam.workspace = true # for ray-traced-triangle example
|
||||
naga = { workspace = true, features = ["wgsl-in", "termcolor"] }
|
||||
winit.workspace = true # for "halmark" example
|
||||
|
||||
### Platform: Windows + MacOS + Linux for "raw-gles" example ###
|
||||
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies]
|
||||
glutin-winit = { workspace = true, features = ["egl", "wgl", "wayland", "x11"] }
|
||||
glutin = { workspace = true, features = ["egl", "wgl", "wayland", "x11"] }
|
||||
Vendored
+176
@@ -0,0 +1,176 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 The gfx-rs developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+119
@@ -0,0 +1,119 @@
|
||||
# `wgpu_hal`: a cross-platform unsafe graphics abstraction
|
||||
|
||||
This crate defines a set of traits abstracting over modern graphics APIs,
|
||||
with implementations ("backends") for Vulkan, Metal, Direct3D, and GL.
|
||||
|
||||
`wgpu_hal` is a spiritual successor to
|
||||
[gfx-hal](https://github.com/gfx-rs/gfx), but with reduced scope, and
|
||||
oriented towards WebGPU implementation goals. It has no overhead for
|
||||
validation or tracking, and the API translation overhead is kept to the bare
|
||||
minimum by the design of WebGPU. This API can be used for resource-demanding
|
||||
applications and engines.
|
||||
|
||||
The `wgpu_hal` crate's main design choices:
|
||||
|
||||
- Our traits are meant to be _portable_: proper use
|
||||
should get equivalent results regardless of the backend.
|
||||
|
||||
- Our traits' contracts are _unsafe_: implementations perform minimal
|
||||
validation, if any, and incorrect use will often cause undefined behavior.
|
||||
This allows us to minimize the overhead we impose over the underlying
|
||||
graphics system. If you need safety, the [`wgpu-core`] crate provides a
|
||||
safe API for driving `wgpu_hal`, implementing all necessary validation,
|
||||
resource state tracking, and so on. (Note that `wgpu-core` is designed for
|
||||
use via FFI; the [`wgpu`] crate provides more idiomatic Rust bindings for
|
||||
`wgpu-core`.) Or, you can do your own validation.
|
||||
|
||||
- In the same vein, returned errors _only cover cases the user can't
|
||||
anticipate_, like running out of memory or losing the device. Any errors
|
||||
that the user could reasonably anticipate are their responsibility to
|
||||
avoid. For example, `wgpu_hal` returns no error for mapping a buffer that's
|
||||
not mappable: as the buffer creator, the user should already know if they
|
||||
can map it.
|
||||
|
||||
- We use _static dispatch_. The traits are not
|
||||
generally object-safe. You must select a specific backend type
|
||||
like [`vulkan::Api`] or [`metal::Api`], and then use that
|
||||
according to the main traits, or call backend-specific methods.
|
||||
|
||||
- We use _idiomatic Rust parameter passing_,
|
||||
taking objects by reference, returning them by value, and so on,
|
||||
unlike `wgpu-core`, which refers to objects by ID.
|
||||
|
||||
- We map buffer contents _persistently_. This means that the buffer
|
||||
can remain mapped on the CPU while the GPU reads or writes to it.
|
||||
You must explicitly indicate when data might need to be
|
||||
transferred between CPU and GPU, if `wgpu_hal` indicates that the
|
||||
mapping is not coherent (that is, automatically synchronized
|
||||
between the two devices).
|
||||
|
||||
- You must record _explicit barriers_ between different usages of a
|
||||
resource. For example, if a buffer is written to by a compute
|
||||
shader, and then used as and index buffer to a draw call, you
|
||||
must use [`CommandEncoder::transition_buffers`] between those two
|
||||
operations.
|
||||
|
||||
- Pipeline layouts are _explicitly specified_ when setting bind
|
||||
group. Incompatible layouts disturb groups bound at higher indices.
|
||||
|
||||
- The API _accepts collections as iterators_, to avoid forcing the user to
|
||||
store data in particular containers. The implementation doesn't guarantee
|
||||
that any of the iterators are drained, unless stated otherwise by the
|
||||
function documentation. For this reason, we recommend that iterators don't
|
||||
do any mutating work.
|
||||
|
||||
Unfortunately, `wgpu_hal`'s safety requirements are not fully documented.
|
||||
Ideally, all trait methods would have doc comments setting out the
|
||||
requirements users must meet to ensure correct and portable behavior. If you
|
||||
are aware of a specific requirement that a backend imposes that is not
|
||||
ensured by the traits' documented rules, please file an issue. Or, if you are
|
||||
a capable technical writer, please file a pull request!
|
||||
|
||||
[`wgpu-core`]: https://crates.io/crates/wgpu-core
|
||||
[`wgpu`]: https://crates.io/crates/wgpu
|
||||
[`vulkan::Api`]: vulkan/struct.Api.html
|
||||
[`metal::Api`]: metal/struct.Api.html
|
||||
|
||||
## Primary backends
|
||||
|
||||
The `wgpu_hal` crate has full-featured backends implemented on the following
|
||||
platform graphics APIs:
|
||||
|
||||
- Vulkan, available on Linux, Android, and Windows, using the [`ash`] crate's
|
||||
Vulkan bindings. It's also available on macOS, if you install [MoltenVK].
|
||||
|
||||
- Metal on macOS, using the [`metal`] crate's bindings.
|
||||
|
||||
- Direct3D 12 on Windows, using the [`windows`] crate's bindings.
|
||||
|
||||
[`ash`]: https://crates.io/crates/ash
|
||||
[MoltenVK]: https://github.com/KhronosGroup/MoltenVK
|
||||
[`metal`]: https://crates.io/crates/metal
|
||||
[`windows`]: https://crates.io/crates/windows
|
||||
|
||||
## Secondary backends
|
||||
|
||||
The `wgpu_hal` crate has a partial implementation based on the following
|
||||
platform graphics API:
|
||||
|
||||
- The GL backend is available anywhere OpenGL, OpenGL ES, or WebGL are
|
||||
available. See the [`gles`] module documentation for details.
|
||||
|
||||
[`gles`]: gles/index.html
|
||||
|
||||
You can see what capabilities an adapter is missing by checking the
|
||||
[`DownlevelCapabilities`][tdc] in [`ExposedAdapter::capabilities`], available
|
||||
from [`Instance::enumerate_adapters`].
|
||||
|
||||
The API is generally designed to fit the primary backends better than the
|
||||
secondary backends, so the latter may impose more overhead.
|
||||
|
||||
[tdc]: wgt::DownlevelCapabilities
|
||||
|
||||
## Debugging
|
||||
|
||||
Most of the information on the wiki [Debugging wgpu Applications][wiki-debug]
|
||||
page still applies to this API, with the exception of API tracing/replay
|
||||
functionality, which is only available in `wgpu-core`.
|
||||
|
||||
[wiki-debug]: https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications
|
||||
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
fn main() {
|
||||
cfg_aliases::cfg_aliases! {
|
||||
native: { not(target_arch = "wasm32") },
|
||||
send_sync: { any(
|
||||
not(target_arch = "wasm32"),
|
||||
all(feature = "fragile-send-sync-non-atomic-wasm", not(target_feature = "atomics"))
|
||||
) },
|
||||
webgl: { all(target_arch = "wasm32", not(target_os = "emscripten"), gles) },
|
||||
Emscripten: { all(target_os = "emscripten", gles) },
|
||||
dx12: { all(target_os = "windows", feature = "dx12") },
|
||||
gles: { all(feature = "gles") },
|
||||
// Within the GL ES backend, use `std` and be Send + Sync only if we are using a target
|
||||
// that, among the ones where the GL ES backend is supported, has `std`.
|
||||
gles_with_std: { all(
|
||||
feature = "gles",
|
||||
any(
|
||||
not(target_arch = "wasm32"),
|
||||
// Accept wasm32-unknown-unknown, which uniquely has a stub `std`
|
||||
all(target_vendor = "unknown", target_os = "unknown"),
|
||||
// Accept wasm32-unknown-emscripten and similar, which has a real `std`
|
||||
target_os = "emscripten"
|
||||
)
|
||||
) },
|
||||
metal: { all(target_vendor = "apple", feature = "metal") },
|
||||
vulkan: { all(not(target_arch = "wasm32"), feature = "vulkan") },
|
||||
drm: { all(
|
||||
feature = "drm",
|
||||
any(target_os = "linux", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd")
|
||||
) },
|
||||
any_backend: { any(dx12, metal, vulkan, gles) },
|
||||
// ⚠️ Keep in sync with target.cfg() definition in Cargo.toml and cfg_alias in `wgpu` crate ⚠️
|
||||
static_dxc: { all(target_os = "windows", feature = "static-dxc", not(target_arch = "aarch64"), target_env = "msvc") },
|
||||
supports_64bit_atomics: { target_has_atomic = "64" },
|
||||
supports_ptr_atomics: { target_has_atomic = "ptr" }
|
||||
}
|
||||
}
|
||||
+919
@@ -0,0 +1,919 @@
|
||||
//! This example shows basic usage of wgpu-hal by rendering
|
||||
//! a ton of moving sprites, each with a separate texture and draw call.
|
||||
extern crate wgpu_hal as hal;
|
||||
|
||||
use hal::{
|
||||
Adapter as _, CommandEncoder as _, Device as _, Instance as _, Queue as _, Surface as _,
|
||||
};
|
||||
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
event::{ElementState, KeyEvent, WindowEvent},
|
||||
event_loop::{ActiveEventLoop, ControlFlow},
|
||||
keyboard::{Key, NamedKey},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
use std::{
|
||||
borrow::{Borrow, Cow},
|
||||
iter,
|
||||
num::NonZeroU64,
|
||||
ptr,
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
const MAX_BUNNIES: usize = 1 << 20;
|
||||
const BUNNY_SIZE: f32 = 0.15 * 256.0;
|
||||
const GRAVITY: f32 = -9.8 * 100.0;
|
||||
const MAX_VELOCITY: f32 = 750.0;
|
||||
const DESIRED_MAX_LATENCY: u32 = 2;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct Globals {
|
||||
mvp: [[f32; 4]; 4],
|
||||
size: [f32; 2],
|
||||
pad: [f32; 2],
|
||||
}
|
||||
|
||||
#[repr(C, align(256))]
|
||||
#[derive(Clone, Copy)]
|
||||
struct Locals {
|
||||
position: [f32; 2],
|
||||
velocity: [f32; 2],
|
||||
color: u32,
|
||||
_pad: u32,
|
||||
}
|
||||
|
||||
struct ExecutionContext<A: hal::Api> {
|
||||
encoder: A::CommandEncoder,
|
||||
fence: A::Fence,
|
||||
fence_value: hal::FenceValue,
|
||||
used_views: Vec<A::TextureView>,
|
||||
used_cmd_bufs: Vec<A::CommandBuffer>,
|
||||
frames_recorded: usize,
|
||||
}
|
||||
|
||||
impl<A: hal::Api> ExecutionContext<A> {
|
||||
unsafe fn wait_and_clear(&mut self, device: &A::Device) {
|
||||
device.wait(&self.fence, self.fence_value, None).unwrap();
|
||||
self.encoder.reset_all(self.used_cmd_bufs.drain(..));
|
||||
for view in self.used_views.drain(..) {
|
||||
device.destroy_texture_view(view);
|
||||
}
|
||||
self.frames_recorded = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
struct Example<A: hal::Api> {
|
||||
instance: A::Instance,
|
||||
adapter: A::Adapter,
|
||||
surface: A::Surface,
|
||||
surface_format: wgpu_types::TextureFormat,
|
||||
device: A::Device,
|
||||
queue: A::Queue,
|
||||
global_group: A::BindGroup,
|
||||
local_group: A::BindGroup,
|
||||
global_group_layout: A::BindGroupLayout,
|
||||
local_group_layout: A::BindGroupLayout,
|
||||
pipeline_layout: A::PipelineLayout,
|
||||
shader: A::ShaderModule,
|
||||
pipeline: A::RenderPipeline,
|
||||
bunnies: Vec<Locals>,
|
||||
local_buffer: A::Buffer,
|
||||
local_alignment: u32,
|
||||
global_buffer: A::Buffer,
|
||||
sampler: A::Sampler,
|
||||
texture: A::Texture,
|
||||
texture_view: A::TextureView,
|
||||
contexts: Vec<ExecutionContext<A>>,
|
||||
context_index: usize,
|
||||
extent: [u32; 2],
|
||||
start: Instant,
|
||||
}
|
||||
|
||||
impl<A: hal::Api> Example<A> {
|
||||
fn init(window: &winit::window::Window) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
// The Instance can be initialized with the DisplayHandle from the EventLoop as well
|
||||
let raw_display_handle = window.display_handle()?;
|
||||
|
||||
let instance_desc = hal::InstanceDescriptor {
|
||||
name: "example",
|
||||
flags: wgpu_types::InstanceFlags::from_build_config().with_env(),
|
||||
memory_budget_thresholds: wgpu_types::MemoryBudgetThresholds::default(),
|
||||
// Can't rely on having DXC available, so use FXC instead
|
||||
backend_options: wgpu_types::BackendOptions::default(),
|
||||
telemetry: None,
|
||||
display: Some(raw_display_handle),
|
||||
};
|
||||
let instance = unsafe { A::Instance::init(&instance_desc)? };
|
||||
let surface = {
|
||||
let raw_window_handle = window.window_handle()?.as_raw();
|
||||
|
||||
unsafe {
|
||||
instance
|
||||
.create_surface(raw_display_handle.as_raw(), raw_window_handle)
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
|
||||
let (adapter, capabilities) = unsafe {
|
||||
let mut adapters = instance.enumerate_adapters(Some(&surface));
|
||||
if adapters.is_empty() {
|
||||
return Err("no adapters found".into());
|
||||
}
|
||||
let exposed = adapters.swap_remove(0);
|
||||
(exposed.adapter, exposed.capabilities)
|
||||
};
|
||||
|
||||
let surface_caps = unsafe { adapter.surface_capabilities(&surface) }
|
||||
.ok_or("failed to get surface capabilities")?;
|
||||
log::info!("Surface caps: {surface_caps:#?}");
|
||||
|
||||
let hal::OpenDevice { device, queue } = unsafe {
|
||||
adapter
|
||||
.open(
|
||||
wgpu_types::Features::empty(),
|
||||
&wgpu_types::Limits::default(),
|
||||
&wgpu_types::MemoryHints::default(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let window_size: (u32, u32) = window.inner_size().into();
|
||||
let surface_config = hal::SurfaceConfiguration {
|
||||
maximum_frame_latency: DESIRED_MAX_LATENCY.clamp(
|
||||
*surface_caps.maximum_frame_latency.start(),
|
||||
*surface_caps.maximum_frame_latency.end(),
|
||||
),
|
||||
present_mode: wgpu_types::PresentMode::Fifo,
|
||||
composite_alpha_mode: wgpu_types::CompositeAlphaMode::Opaque,
|
||||
format: wgpu_types::TextureFormat::Bgra8UnormSrgb,
|
||||
color_space: wgpu_types::SurfaceColorSpace::Srgb,
|
||||
extent: wgpu_types::Extent3d {
|
||||
width: window_size.0,
|
||||
height: window_size.1,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
view_formats: vec![],
|
||||
};
|
||||
unsafe {
|
||||
surface.configure(&device, &surface_config).unwrap();
|
||||
};
|
||||
|
||||
let naga_shader = {
|
||||
let shader_file = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("examples")
|
||||
.join("halmark")
|
||||
.join("shader.wgsl");
|
||||
let source = std::fs::read_to_string(shader_file).unwrap();
|
||||
let module = naga::front::wgsl::Frontend::new().parse(&source).unwrap();
|
||||
let info = naga::valid::Validator::new(
|
||||
naga::valid::ValidationFlags::all(),
|
||||
naga::valid::Capabilities::empty(),
|
||||
)
|
||||
.validate(&module)
|
||||
.unwrap();
|
||||
hal::NagaShader {
|
||||
module: Cow::Owned(module),
|
||||
info,
|
||||
debug_source: None,
|
||||
}
|
||||
};
|
||||
let shader_desc = hal::ShaderModuleDescriptor {
|
||||
label: None,
|
||||
runtime_checks: wgpu_types::ShaderRuntimeChecks::checked(),
|
||||
};
|
||||
let shader = unsafe {
|
||||
device
|
||||
.create_shader_module(&shader_desc, hal::ShaderInput::Naga(naga_shader))
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let global_bgl_desc = hal::BindGroupLayoutDescriptor {
|
||||
label: None,
|
||||
flags: hal::BindGroupLayoutFlags::empty(),
|
||||
entries: &[
|
||||
wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu_types::ShaderStages::VERTEX,
|
||||
ty: wgpu_types::BindingType::Buffer {
|
||||
ty: wgpu_types::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: wgpu_types::BufferSize::new(size_of::<Globals>() as _),
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu_types::ShaderStages::FRAGMENT,
|
||||
ty: wgpu_types::BindingType::Texture {
|
||||
sample_type: wgpu_types::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu_types::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu_types::ShaderStages::FRAGMENT,
|
||||
ty: wgpu_types::BindingType::Sampler(wgpu_types::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let global_group_layout =
|
||||
unsafe { device.create_bind_group_layout(&global_bgl_desc).unwrap() };
|
||||
|
||||
let local_bgl_desc = hal::BindGroupLayoutDescriptor {
|
||||
label: None,
|
||||
flags: hal::BindGroupLayoutFlags::empty(),
|
||||
entries: &[wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu_types::ShaderStages::VERTEX,
|
||||
ty: wgpu_types::BindingType::Buffer {
|
||||
ty: wgpu_types::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: true,
|
||||
min_binding_size: wgpu_types::BufferSize::new(size_of::<Locals>() as _),
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
};
|
||||
let local_group_layout =
|
||||
unsafe { device.create_bind_group_layout(&local_bgl_desc).unwrap() };
|
||||
|
||||
let pipeline_layout_desc = hal::PipelineLayoutDescriptor {
|
||||
label: None,
|
||||
flags: hal::PipelineLayoutFlags::empty(),
|
||||
bind_group_layouts: &[Some(&global_group_layout), Some(&local_group_layout)],
|
||||
immediate_size: 0,
|
||||
};
|
||||
let pipeline_layout = unsafe {
|
||||
device
|
||||
.create_pipeline_layout(&pipeline_layout_desc)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let constants = naga::back::PipelineConstants::default();
|
||||
let pipeline_desc = hal::RenderPipelineDescriptor {
|
||||
label: None,
|
||||
layout: &pipeline_layout,
|
||||
vertex_processor: hal::VertexProcessor::Standard {
|
||||
vertex_stage: hal::ProgrammableStage {
|
||||
module: &shader,
|
||||
entry_point: "vs_main",
|
||||
constants: &constants,
|
||||
zero_initialize_workgroup_memory: true,
|
||||
},
|
||||
vertex_buffers: &[],
|
||||
},
|
||||
fragment_stage: Some(hal::ProgrammableStage {
|
||||
module: &shader,
|
||||
entry_point: "fs_main",
|
||||
constants: &constants,
|
||||
zero_initialize_workgroup_memory: true,
|
||||
}),
|
||||
primitive: wgpu_types::PrimitiveState {
|
||||
topology: wgpu_types::PrimitiveTopology::TriangleStrip,
|
||||
..wgpu_types::PrimitiveState::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu_types::MultisampleState::default(),
|
||||
color_targets: &[Some(wgpu_types::ColorTargetState {
|
||||
format: surface_config.format,
|
||||
blend: Some(wgpu_types::BlendState::ALPHA_BLENDING),
|
||||
write_mask: wgpu_types::ColorWrites::default(),
|
||||
})],
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
};
|
||||
let pipeline = unsafe { device.create_render_pipeline(&pipeline_desc).unwrap() };
|
||||
|
||||
let texture_data = [0xFFu8; 4];
|
||||
|
||||
let staging_buffer_desc = hal::BufferDescriptor {
|
||||
label: Some("stage"),
|
||||
size: texture_data.len() as wgpu_types::BufferAddress,
|
||||
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::COPY_SRC,
|
||||
memory_flags: hal::MemoryFlags::TRANSIENT | hal::MemoryFlags::PREFER_COHERENT,
|
||||
};
|
||||
let staging_buffer = unsafe { device.create_buffer(&staging_buffer_desc).unwrap() };
|
||||
unsafe {
|
||||
let mapping = device
|
||||
.map_buffer(&staging_buffer, 0..staging_buffer_desc.size)
|
||||
.unwrap();
|
||||
ptr::copy_nonoverlapping(
|
||||
texture_data.as_ptr(),
|
||||
mapping.ptr.as_ptr(),
|
||||
texture_data.len(),
|
||||
);
|
||||
device.unmap_buffer(&staging_buffer);
|
||||
assert!(mapping.is_coherent);
|
||||
}
|
||||
|
||||
let texture_desc = hal::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu_types::Extent3d {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu_types::TextureDimension::D2,
|
||||
format: wgpu_types::TextureFormat::Rgba8UnormSrgb,
|
||||
usage: wgpu_types::TextureUses::COPY_DST | wgpu_types::TextureUses::RESOURCE,
|
||||
memory_flags: hal::MemoryFlags::empty(),
|
||||
view_formats: vec![],
|
||||
};
|
||||
let texture = unsafe { device.create_texture(&texture_desc).unwrap() };
|
||||
|
||||
let cmd_encoder_desc = hal::CommandEncoderDescriptor {
|
||||
label: None,
|
||||
queue: &queue,
|
||||
};
|
||||
let mut cmd_encoder = unsafe { device.create_command_encoder(&cmd_encoder_desc).unwrap() };
|
||||
unsafe { cmd_encoder.begin_encoding(Some("init")).unwrap() };
|
||||
{
|
||||
let buffer_barrier = hal::BufferBarrier {
|
||||
buffer: &staging_buffer,
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::BufferUses::empty(),
|
||||
to: wgpu_types::BufferUses::COPY_SRC,
|
||||
},
|
||||
};
|
||||
let texture_barrier1 = hal::TextureBarrier {
|
||||
texture: &texture,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::UNINITIALIZED,
|
||||
to: wgpu_types::TextureUses::COPY_DST,
|
||||
},
|
||||
};
|
||||
let texture_barrier2 = hal::TextureBarrier {
|
||||
texture: &texture,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::COPY_DST,
|
||||
to: wgpu_types::TextureUses::RESOURCE,
|
||||
},
|
||||
};
|
||||
let copy = hal::BufferTextureCopy {
|
||||
buffer_layout: wgpu_types::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(4),
|
||||
rows_per_image: None,
|
||||
},
|
||||
texture_base: hal::TextureCopyBase {
|
||||
origin: wgpu_types::Origin3d::ZERO,
|
||||
mip_level: 0,
|
||||
array_layer: 0,
|
||||
aspect: hal::FormatAspects::COLOR,
|
||||
},
|
||||
size: hal::CopyExtent {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth: 1,
|
||||
},
|
||||
};
|
||||
unsafe {
|
||||
cmd_encoder.transition_buffers(iter::once(buffer_barrier));
|
||||
cmd_encoder.transition_textures(iter::once(texture_barrier1));
|
||||
cmd_encoder.copy_buffer_to_texture(&staging_buffer, &texture, iter::once(copy));
|
||||
cmd_encoder.transition_textures(iter::once(texture_barrier2));
|
||||
}
|
||||
}
|
||||
|
||||
let sampler_desc = hal::SamplerDescriptor {
|
||||
label: None,
|
||||
address_modes: [wgpu_types::AddressMode::ClampToEdge; 3],
|
||||
mag_filter: wgpu_types::FilterMode::Linear,
|
||||
min_filter: wgpu_types::FilterMode::Nearest,
|
||||
mipmap_filter: wgpu_types::MipmapFilterMode::Nearest,
|
||||
lod_clamp: 0.0..32.0,
|
||||
compare: None,
|
||||
anisotropy_clamp: 1,
|
||||
border_color: None,
|
||||
};
|
||||
let sampler = unsafe { device.create_sampler(&sampler_desc).unwrap() };
|
||||
|
||||
let globals = Globals {
|
||||
// cgmath::ortho() projection
|
||||
mvp: [
|
||||
[2.0 / window_size.0 as f32, 0.0, 0.0, 0.0],
|
||||
[0.0, 2.0 / window_size.1 as f32, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[-1.0, -1.0, 0.0, 1.0],
|
||||
],
|
||||
size: [BUNNY_SIZE; 2],
|
||||
pad: [0.0; 2],
|
||||
};
|
||||
|
||||
let global_buffer_desc = hal::BufferDescriptor {
|
||||
label: Some("global"),
|
||||
size: size_of::<Globals>() as wgpu_types::BufferAddress,
|
||||
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM,
|
||||
memory_flags: hal::MemoryFlags::PREFER_COHERENT,
|
||||
};
|
||||
let global_buffer = unsafe {
|
||||
let buffer = device.create_buffer(&global_buffer_desc).unwrap();
|
||||
let mapping = device
|
||||
.map_buffer(&buffer, 0..global_buffer_desc.size)
|
||||
.unwrap();
|
||||
ptr::copy_nonoverlapping(
|
||||
&globals as *const Globals as *const u8,
|
||||
mapping.ptr.as_ptr(),
|
||||
size_of::<Globals>(),
|
||||
);
|
||||
device.unmap_buffer(&buffer);
|
||||
assert!(mapping.is_coherent);
|
||||
buffer
|
||||
};
|
||||
|
||||
let local_alignment = wgpu_types::math::align_to(
|
||||
size_of::<Locals>() as u32,
|
||||
capabilities.limits.min_uniform_buffer_offset_alignment,
|
||||
);
|
||||
let local_buffer_desc = hal::BufferDescriptor {
|
||||
label: Some("local"),
|
||||
size: (MAX_BUNNIES as wgpu_types::BufferAddress)
|
||||
* (local_alignment as wgpu_types::BufferAddress),
|
||||
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM,
|
||||
memory_flags: hal::MemoryFlags::PREFER_COHERENT,
|
||||
};
|
||||
let local_buffer = unsafe { device.create_buffer(&local_buffer_desc).unwrap() };
|
||||
|
||||
let view_desc = hal::TextureViewDescriptor {
|
||||
label: None,
|
||||
format: texture_desc.format,
|
||||
dimension: wgpu_types::TextureViewDimension::D2,
|
||||
usage: wgpu_types::TextureUses::RESOURCE,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
};
|
||||
let texture_view = unsafe { device.create_texture_view(&texture, &view_desc).unwrap() };
|
||||
|
||||
let global_group = {
|
||||
// SAFETY: This is the same size that was specified for buffer creation.
|
||||
let global_buffer_binding = hal::BufferBinding::new_unchecked(
|
||||
&global_buffer,
|
||||
0,
|
||||
NonZeroU64::new(global_buffer_desc.size),
|
||||
);
|
||||
let texture_binding = hal::TextureBinding {
|
||||
view: &texture_view,
|
||||
usage: wgpu_types::TextureUses::RESOURCE,
|
||||
};
|
||||
let global_group_desc = hal::BindGroupDescriptor {
|
||||
label: Some("global"),
|
||||
layout: &global_group_layout,
|
||||
buffers: &[global_buffer_binding],
|
||||
samplers: &[&sampler],
|
||||
textures: &[texture_binding],
|
||||
acceleration_structures: &[],
|
||||
external_textures: &[],
|
||||
entries: &[
|
||||
hal::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
},
|
||||
hal::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
},
|
||||
hal::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
unsafe { device.create_bind_group(&global_group_desc).unwrap() }
|
||||
};
|
||||
|
||||
let local_group = {
|
||||
// SAFETY: The size must fit within the buffer.
|
||||
let local_buffer_binding = hal::BufferBinding::new_unchecked(
|
||||
&local_buffer,
|
||||
0,
|
||||
wgpu_types::BufferSize::new(size_of::<Locals>() as _),
|
||||
);
|
||||
let local_group_desc = hal::BindGroupDescriptor {
|
||||
label: Some("local"),
|
||||
layout: &local_group_layout,
|
||||
buffers: &[local_buffer_binding],
|
||||
samplers: &[],
|
||||
textures: &[],
|
||||
acceleration_structures: &[],
|
||||
external_textures: &[],
|
||||
entries: &[hal::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
}],
|
||||
};
|
||||
unsafe { device.create_bind_group(&local_group_desc).unwrap() }
|
||||
};
|
||||
|
||||
let init_fence_value = 1;
|
||||
let fence = unsafe {
|
||||
let mut fence = device.create_fence().unwrap();
|
||||
let init_cmd = cmd_encoder.end_encoding().unwrap();
|
||||
queue
|
||||
.submit(&[&init_cmd], &[], (&mut fence, init_fence_value))
|
||||
.unwrap();
|
||||
device.wait(&fence, init_fence_value, None).unwrap();
|
||||
device.destroy_buffer(staging_buffer);
|
||||
cmd_encoder.reset_all(iter::once(init_cmd));
|
||||
fence
|
||||
};
|
||||
|
||||
Ok(Example {
|
||||
instance,
|
||||
surface,
|
||||
surface_format: surface_config.format,
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
pipeline_layout,
|
||||
shader,
|
||||
pipeline,
|
||||
global_group,
|
||||
local_group,
|
||||
global_group_layout,
|
||||
local_group_layout,
|
||||
bunnies: Vec::new(),
|
||||
local_buffer,
|
||||
local_alignment,
|
||||
global_buffer,
|
||||
sampler,
|
||||
texture,
|
||||
texture_view,
|
||||
contexts: vec![ExecutionContext {
|
||||
encoder: cmd_encoder,
|
||||
fence,
|
||||
fence_value: init_fence_value + 1,
|
||||
used_views: Vec::new(),
|
||||
used_cmd_bufs: Vec::new(),
|
||||
frames_recorded: 0,
|
||||
}],
|
||||
context_index: 0,
|
||||
extent: [window_size.0, window_size.1],
|
||||
start: Instant::now(),
|
||||
})
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.bunnies.is_empty()
|
||||
}
|
||||
|
||||
fn exit(mut self) {
|
||||
unsafe {
|
||||
{
|
||||
let ctx = &mut self.contexts[self.context_index];
|
||||
self.queue
|
||||
.submit(&[], &[], (&mut ctx.fence, ctx.fence_value))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
for mut ctx in self.contexts {
|
||||
ctx.wait_and_clear(&self.device);
|
||||
drop(ctx.encoder);
|
||||
self.device.destroy_fence(ctx.fence);
|
||||
}
|
||||
|
||||
self.device.destroy_bind_group(self.local_group);
|
||||
self.device.destroy_bind_group(self.global_group);
|
||||
self.device.destroy_buffer(self.local_buffer);
|
||||
self.device.destroy_buffer(self.global_buffer);
|
||||
self.device.destroy_texture_view(self.texture_view);
|
||||
self.device.destroy_texture(self.texture);
|
||||
self.device.destroy_sampler(self.sampler);
|
||||
self.device.destroy_shader_module(self.shader);
|
||||
self.device.destroy_render_pipeline(self.pipeline);
|
||||
self.device
|
||||
.destroy_bind_group_layout(self.local_group_layout);
|
||||
self.device
|
||||
.destroy_bind_group_layout(self.global_group_layout);
|
||||
self.device.destroy_pipeline_layout(self.pipeline_layout);
|
||||
|
||||
self.surface.unconfigure(&self.device);
|
||||
drop(self.queue);
|
||||
drop(self.device);
|
||||
drop(self.surface);
|
||||
drop(self.adapter);
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, event: winit::event::WindowEvent) {
|
||||
if let winit::event::WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: Key::Named(NamedKey::Space),
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} = event
|
||||
{
|
||||
let spawn_count = 64 + self.bunnies.len() / 2;
|
||||
let elapsed = self.start.elapsed();
|
||||
let color = elapsed.as_nanos() as u32;
|
||||
println!(
|
||||
"Spawning {} bunnies, total at {}",
|
||||
spawn_count,
|
||||
self.bunnies.len() + spawn_count
|
||||
);
|
||||
for i in 0..spawn_count {
|
||||
let random = ((elapsed.as_nanos() * (i + 1) as u128) & 0xFF) as f32 / 255.0;
|
||||
let speed = random * MAX_VELOCITY - (MAX_VELOCITY * 0.5);
|
||||
self.bunnies.push(Locals {
|
||||
position: [0.0, 0.5 * (self.extent[1] as f32)],
|
||||
velocity: [speed, 0.0],
|
||||
color,
|
||||
_pad: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render(&mut self) {
|
||||
let delta = 0.01;
|
||||
for bunny in self.bunnies.iter_mut() {
|
||||
bunny.position[0] += bunny.velocity[0] * delta;
|
||||
bunny.position[1] += bunny.velocity[1] * delta;
|
||||
bunny.velocity[1] += GRAVITY * delta;
|
||||
if (bunny.velocity[0] > 0.0
|
||||
&& bunny.position[0] + 0.5 * BUNNY_SIZE > self.extent[0] as f32)
|
||||
|| (bunny.velocity[0] < 0.0 && bunny.position[0] - 0.5 * BUNNY_SIZE < 0.0)
|
||||
{
|
||||
bunny.velocity[0] *= -1.0;
|
||||
}
|
||||
if bunny.velocity[1] < 0.0 && bunny.position[1] < 0.5 * BUNNY_SIZE {
|
||||
bunny.velocity[1] *= -1.0;
|
||||
}
|
||||
}
|
||||
|
||||
if !self.bunnies.is_empty() {
|
||||
let size = self.bunnies.len() * self.local_alignment as usize;
|
||||
unsafe {
|
||||
let mapping = self
|
||||
.device
|
||||
.map_buffer(&self.local_buffer, 0..size as wgpu_types::BufferAddress)
|
||||
.unwrap();
|
||||
ptr::copy_nonoverlapping(
|
||||
self.bunnies.as_ptr() as *const u8,
|
||||
mapping.ptr.as_ptr(),
|
||||
size,
|
||||
);
|
||||
assert!(mapping.is_coherent);
|
||||
self.device.unmap_buffer(&self.local_buffer);
|
||||
}
|
||||
}
|
||||
|
||||
let ctx = &mut self.contexts[self.context_index];
|
||||
|
||||
let surface_tex = unsafe {
|
||||
self.surface
|
||||
.acquire_texture(None, &ctx.fence)
|
||||
.unwrap()
|
||||
.texture
|
||||
};
|
||||
|
||||
let target_barrier0 = hal::TextureBarrier {
|
||||
texture: surface_tex.borrow(),
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::UNINITIALIZED,
|
||||
to: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
},
|
||||
};
|
||||
unsafe {
|
||||
ctx.encoder.begin_encoding(Some("frame")).unwrap();
|
||||
ctx.encoder.transition_textures(iter::once(target_barrier0));
|
||||
}
|
||||
|
||||
let surface_view_desc = hal::TextureViewDescriptor {
|
||||
label: None,
|
||||
format: self.surface_format,
|
||||
dimension: wgpu_types::TextureViewDimension::D2,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
};
|
||||
let surface_tex_view = unsafe {
|
||||
self.device
|
||||
.create_texture_view(surface_tex.borrow(), &surface_view_desc)
|
||||
.unwrap()
|
||||
};
|
||||
let pass_desc = hal::RenderPassDescriptor {
|
||||
label: None,
|
||||
extent: wgpu_types::Extent3d {
|
||||
width: self.extent[0],
|
||||
height: self.extent[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
sample_count: 1,
|
||||
color_attachments: &[Some(hal::ColorAttachment {
|
||||
target: hal::Attachment {
|
||||
view: &surface_tex_view,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
},
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: hal::AttachmentOps::STORE | hal::AttachmentOps::LOAD_CLEAR,
|
||||
clear_value: wgpu_types::Color {
|
||||
r: 0.1,
|
||||
g: 0.2,
|
||||
b: 0.3,
|
||||
a: 1.0,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
multiview_mask: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
};
|
||||
unsafe {
|
||||
ctx.encoder.begin_render_pass(&pass_desc).unwrap();
|
||||
ctx.encoder.set_render_pipeline(&self.pipeline);
|
||||
ctx.encoder
|
||||
.set_bind_group(&self.pipeline_layout, 0, &self.global_group, &[]);
|
||||
}
|
||||
|
||||
for i in 0..self.bunnies.len() {
|
||||
let offset = (i as wgpu_types::DynamicOffset)
|
||||
* (self.local_alignment as wgpu_types::DynamicOffset);
|
||||
unsafe {
|
||||
ctx.encoder
|
||||
.set_bind_group(&self.pipeline_layout, 1, &self.local_group, &[offset]);
|
||||
ctx.encoder.draw(0, 4, 0, 1);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.frames_recorded += 1;
|
||||
|
||||
let target_barrier1 = hal::TextureBarrier {
|
||||
texture: surface_tex.borrow(),
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
to: wgpu_types::TextureUses::PRESENT,
|
||||
},
|
||||
};
|
||||
unsafe {
|
||||
ctx.encoder.end_render_pass();
|
||||
ctx.encoder.transition_textures(iter::once(target_barrier1));
|
||||
}
|
||||
|
||||
unsafe {
|
||||
let cmd_buf = ctx.encoder.end_encoding().unwrap();
|
||||
self.queue
|
||||
.submit(
|
||||
&[&cmd_buf],
|
||||
&[&surface_tex],
|
||||
(&mut ctx.fence, ctx.fence_value),
|
||||
)
|
||||
.unwrap();
|
||||
self.queue.present(&self.surface, surface_tex).unwrap();
|
||||
ctx.used_cmd_bufs.push(cmd_buf);
|
||||
ctx.used_views.push(surface_tex_view);
|
||||
};
|
||||
|
||||
log::debug!("Context switch from {}", self.context_index);
|
||||
let old_fence_value = ctx.fence_value;
|
||||
if self.contexts.len() == 1 {
|
||||
let hal_desc = hal::CommandEncoderDescriptor {
|
||||
label: None,
|
||||
queue: &self.queue,
|
||||
};
|
||||
self.contexts.push(unsafe {
|
||||
ExecutionContext {
|
||||
encoder: self.device.create_command_encoder(&hal_desc).unwrap(),
|
||||
fence: self.device.create_fence().unwrap(),
|
||||
fence_value: 0,
|
||||
used_views: Vec::new(),
|
||||
used_cmd_bufs: Vec::new(),
|
||||
frames_recorded: 0,
|
||||
}
|
||||
});
|
||||
}
|
||||
self.context_index = (self.context_index + 1) % self.contexts.len();
|
||||
let next = &mut self.contexts[self.context_index];
|
||||
unsafe {
|
||||
next.wait_and_clear(&self.device);
|
||||
}
|
||||
next.fence_value = old_fence_value + 1;
|
||||
}
|
||||
}
|
||||
|
||||
cfg_if::cfg_if! {
|
||||
// Apple + Metal
|
||||
if #[cfg(all(target_vendor = "apple", feature = "metal"))] {
|
||||
type Api = hal::api::Metal;
|
||||
}
|
||||
// Wasm + Vulkan
|
||||
else if #[cfg(all(not(target_arch = "wasm32"), feature = "vulkan"))] {
|
||||
type Api = hal::api::Vulkan;
|
||||
}
|
||||
// Windows + DX12
|
||||
else if #[cfg(all(windows, feature = "dx12"))] {
|
||||
type Api = hal::api::Dx12;
|
||||
}
|
||||
// Anything + GLES
|
||||
else if #[cfg(feature = "gles")] {
|
||||
type Api = hal::api::Gles;
|
||||
}
|
||||
// Fallback
|
||||
else {
|
||||
type Api = hal::api::Noop;
|
||||
}
|
||||
}
|
||||
|
||||
struct App {
|
||||
example: Option<Example<Api>>,
|
||||
window: Option<Window>,
|
||||
last_frame_inst: Instant,
|
||||
frame_count: u32,
|
||||
accum_time: f32,
|
||||
}
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_some() {
|
||||
return;
|
||||
}
|
||||
let window = event_loop
|
||||
.create_window(Window::default_attributes().with_title("hal-bunnymark"))
|
||||
.unwrap();
|
||||
let example = Example::<Api>::init(&window).expect("Selected backend is not supported");
|
||||
self.window = Some(window);
|
||||
self.example = Some(example);
|
||||
println!("Press space to spawn bunnies.");
|
||||
self.window.as_ref().unwrap().request_redraw();
|
||||
}
|
||||
|
||||
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
self.example.take().unwrap().exit();
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_window_id: winit::window::WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
|
||||
match event {
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: Key::Named(NamedKey::Escape),
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
}
|
||||
| WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::RedrawRequested => {
|
||||
let ex = self.example.as_mut().unwrap();
|
||||
{
|
||||
self.accum_time += self.last_frame_inst.elapsed().as_secs_f32();
|
||||
self.last_frame_inst = Instant::now();
|
||||
self.frame_count += 1;
|
||||
if self.frame_count == 100 && !ex.is_empty() {
|
||||
println!(
|
||||
"Avg frame time {}ms",
|
||||
self.accum_time * 1000.0 / self.frame_count as f32
|
||||
);
|
||||
self.accum_time = 0.0;
|
||||
self.frame_count = 0;
|
||||
}
|
||||
}
|
||||
ex.render();
|
||||
self.window.as_ref().unwrap().request_redraw();
|
||||
}
|
||||
_ => {
|
||||
self.example.as_mut().unwrap().update(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
|
||||
let event_loop = winit::event_loop::EventLoop::new().unwrap();
|
||||
let mut app = App {
|
||||
example: None,
|
||||
window: None,
|
||||
last_frame_inst: Instant::now(),
|
||||
frame_count: 0,
|
||||
accum_time: 0.0,
|
||||
};
|
||||
event_loop.run_app(&mut app).unwrap();
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
struct Globals {
|
||||
mvp: mat4x4<f32>,
|
||||
size: vec2<f32>,
|
||||
_pad0: u32,
|
||||
_pad1: u32,
|
||||
};
|
||||
|
||||
struct Locals {
|
||||
position: vec2<f32>,
|
||||
velocity: vec2<f32>,
|
||||
color: u32,
|
||||
_pad0: u32,
|
||||
_pad1: u32,
|
||||
_pad2: u32,
|
||||
};
|
||||
|
||||
@group(0)
|
||||
@binding(0)
|
||||
var<uniform> globals: Globals;
|
||||
|
||||
@group(1)
|
||||
@binding(0)
|
||||
var<uniform> locals: Locals;
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) tex_coords: vec2<f32>,
|
||||
@location(1) color: vec4<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vi: u32) -> VertexOutput {
|
||||
let tc = vec2<f32>(f32(vi & 1u), 0.5 * f32(vi & 2u));
|
||||
let offset = vec2<f32>(tc.x * globals.size.x, tc.y * globals.size.y);
|
||||
let pos = globals.mvp * vec4<f32>(locals.position + offset, 0.0, 1.0);
|
||||
let color = vec4<f32>((vec4<u32>(locals.color) >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(255u)) / 255.0;
|
||||
return VertexOutput(pos, tc, color);
|
||||
}
|
||||
|
||||
@group(0)
|
||||
@binding(1)
|
||||
var tex: texture_2d<f32>;
|
||||
@group(0)
|
||||
@binding(2)
|
||||
var sam: sampler;
|
||||
|
||||
@fragment
|
||||
fn fs_main(vertex: VertexOutput) -> @location(0) vec4<f32> {
|
||||
return vertex.color * textureSampleLevel(tex, sam, vertex.tex_coords, 0.0);
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="canvas" width="640" height="400"></canvas>
|
||||
<script>
|
||||
var Module = {
|
||||
canvas: document.getElementById("canvas"),
|
||||
preRun: [
|
||||
function () {
|
||||
ENV.RUST_LOG = "debug";
|
||||
},
|
||||
],
|
||||
};
|
||||
</script>
|
||||
<script src="raw-gles.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Vendored
+396
@@ -0,0 +1,396 @@
|
||||
//! This example shows interop with raw GLES contexts -
|
||||
//! the ability to hook up wgpu-hal to an existing context and draw into it.
|
||||
//!
|
||||
//! Emscripten build:
|
||||
//! 1. install emsdk
|
||||
//! 2. build this example with cargo:
|
||||
//! EMCC_CFLAGS="-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 --no-entry -s FULL_ES3=1" cargo build --example raw-gles --target wasm32-unknown-emscripten
|
||||
//! 3. copy raw-gles.em.html into target directory and open it in browser:
|
||||
//! cp wgpu-hal/examples/raw-gles.em.html target/wasm32-unknown-emscripten/debug/examples
|
||||
|
||||
extern crate wgpu_hal as hal;
|
||||
|
||||
#[cfg(not(any(
|
||||
target_arch = "wasm32",
|
||||
target_os = "ios",
|
||||
target_os = "visionos",
|
||||
target_env = "ohos"
|
||||
)))]
|
||||
fn main() {
|
||||
use std::ffi::CString;
|
||||
|
||||
use glutin::{
|
||||
config::GlConfig as _,
|
||||
context::{NotCurrentGlContext as _, PossiblyCurrentGlContext as _, Version},
|
||||
display::{GetGlDisplay as _, GlDisplay as _},
|
||||
surface::GlSurface as _,
|
||||
};
|
||||
use glutin_winit::GlWindow as _;
|
||||
use raw_window_handle::HasWindowHandle as _;
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
event::{KeyEvent, WindowEvent},
|
||||
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
|
||||
keyboard::{Key, NamedKey},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
env_logger::init();
|
||||
println!("Initializing external GL context");
|
||||
|
||||
/// Find the config with the maximum number of samples, so our triangle will be
|
||||
/// smooth.
|
||||
fn gl_config_picker(
|
||||
configs: Box<dyn Iterator<Item = glutin::config::Config> + '_>,
|
||||
) -> glutin::config::Config {
|
||||
configs
|
||||
.reduce(|accum, config| {
|
||||
if config.num_samples() > accum.num_samples() {
|
||||
config
|
||||
} else {
|
||||
accum
|
||||
}
|
||||
})
|
||||
.expect("Failed to find a matching config")
|
||||
}
|
||||
|
||||
struct App {
|
||||
gl_config: Option<glutin::config::Config>,
|
||||
not_current_gl_context: Option<glutin::context::NotCurrentContext>,
|
||||
state: Option<(
|
||||
glutin::context::PossiblyCurrentContext,
|
||||
glutin::surface::Surface<glutin::surface::WindowSurface>,
|
||||
Window,
|
||||
)>,
|
||||
exposed: Option<hal::ExposedAdapter<hal::api::Gles>>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
gl_config: None,
|
||||
not_current_gl_context: None,
|
||||
state: None,
|
||||
exposed: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
// First call: create display, pick config, create GL context.
|
||||
if self.gl_config.is_none() {
|
||||
// Only Windows requires the window to be present before creating the display.
|
||||
// Other platforms don't really need one.
|
||||
let window_attributes = cfg!(windows).then(|| {
|
||||
Window::default_attributes()
|
||||
.with_title("wgpu raw GLES example (press Escape to exit)")
|
||||
});
|
||||
|
||||
let template = glutin::config::ConfigTemplateBuilder::new();
|
||||
|
||||
let display_builder =
|
||||
glutin_winit::DisplayBuilder::new().with_window_attributes(window_attributes);
|
||||
|
||||
let (window, gl_config) = display_builder
|
||||
.build(event_loop, template, gl_config_picker)
|
||||
.expect("Failed to build window and config from display");
|
||||
|
||||
println!("Picked a config with {} samples", gl_config.num_samples());
|
||||
|
||||
let raw_window_handle = window
|
||||
.as_ref()
|
||||
.and_then(|window| window.window_handle().ok())
|
||||
.map(|handle| handle.as_raw());
|
||||
|
||||
let gl_display = gl_config.display();
|
||||
|
||||
// Glutin tries to create an OpenGL context by default.
|
||||
// Force it to use any version of GLES.
|
||||
let context_attributes = glutin::context::ContextAttributesBuilder::new()
|
||||
// wgpu expects GLES 3.0+.
|
||||
.with_context_api(glutin::context::ContextApi::Gles(Some(Version::new(3, 0))))
|
||||
.build(raw_window_handle);
|
||||
|
||||
let gl_context = unsafe {
|
||||
gl_display
|
||||
.create_context(&gl_config, &context_attributes)
|
||||
.expect("failed to create context")
|
||||
};
|
||||
|
||||
self.not_current_gl_context = Some(gl_context);
|
||||
self.gl_config = Some(gl_config);
|
||||
|
||||
// On Windows, the window was already created by DisplayBuilder.
|
||||
if let Some(window) = window {
|
||||
self.create_surface(event_loop, window);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Create window + surface (non-Windows first call, or Android re-resume).
|
||||
if self.state.is_none() {
|
||||
let gl_config = self.gl_config.as_ref().unwrap();
|
||||
let window = glutin_winit::finalize_window(
|
||||
event_loop,
|
||||
Window::default_attributes()
|
||||
.with_title("wgpu raw GLES example (press Escape to exit)"),
|
||||
gl_config,
|
||||
)
|
||||
.unwrap();
|
||||
self.create_surface(event_loop, window);
|
||||
}
|
||||
}
|
||||
|
||||
fn suspended(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
// This event is only raised on Android, where the backing NativeWindow for a GL
|
||||
// Surface can appear and disappear at any moment.
|
||||
println!("Android window removed");
|
||||
|
||||
// Destroy the GL Surface and un-current the GL Context before ndk-glue releases
|
||||
// the window back to the system.
|
||||
if let Some((gl_context, ..)) = self.state.take() {
|
||||
assert!(self
|
||||
.not_current_gl_context
|
||||
.replace(gl_context.make_not_current().unwrap())
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_window_id: winit::window::WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
event_loop.set_control_flow(ControlFlow::Wait);
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested
|
||||
| WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: Key::Named(NamedKey::Escape),
|
||||
..
|
||||
},
|
||||
..
|
||||
} => event_loop.exit(),
|
||||
WindowEvent::Resized(size) => {
|
||||
if size.width != 0 && size.height != 0 {
|
||||
// Some platforms like EGL require resizing GL surface to update the size.
|
||||
// Notable platforms here are Wayland and macOS, other don't require it
|
||||
// and the function is no-op, but it's wise to resize it for portability
|
||||
// reasons.
|
||||
if let Some((gl_context, gl_surface, window)) = &self.state {
|
||||
window.resize_surface(gl_surface, gl_context);
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
if let (Some(exposed), Some((gl_context, gl_surface, window))) =
|
||||
(&self.exposed, &self.state)
|
||||
{
|
||||
let inner_size = window.inner_size();
|
||||
|
||||
fill_screen(exposed, inner_size.width, inner_size.height);
|
||||
|
||||
println!("Showing the window");
|
||||
gl_surface
|
||||
.swap_buffers(gl_context)
|
||||
.expect("Failed to swap buffers");
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn create_surface(&mut self, _event_loop: &ActiveEventLoop, window: Window) {
|
||||
let gl_config = self.gl_config.as_ref().unwrap();
|
||||
|
||||
let attrs = window
|
||||
.build_surface_attributes(Default::default())
|
||||
.expect("Failed to build surface attributes");
|
||||
let gl_surface = unsafe {
|
||||
gl_config
|
||||
.display()
|
||||
.create_window_surface(gl_config, &attrs)
|
||||
.expect("Cannot create GL WindowSurface")
|
||||
};
|
||||
|
||||
// Make it current.
|
||||
let gl_context = self
|
||||
.not_current_gl_context
|
||||
.take()
|
||||
.unwrap()
|
||||
.make_current(&gl_surface)
|
||||
.expect("GL context cannot be made current with WindowSurface");
|
||||
|
||||
// The context needs to be current for the Renderer to set up shaders and
|
||||
// buffers. It also performs function loading, which needs a current context on
|
||||
// WGL.
|
||||
println!("Hooking up to wgpu-hal");
|
||||
self.exposed.get_or_insert_with(|| {
|
||||
unsafe {
|
||||
<hal::api::Gles as hal::Api>::Adapter::new_external(
|
||||
|name| {
|
||||
// XXX: On WGL this should only be called after the context was
|
||||
// made current
|
||||
gl_config
|
||||
.display()
|
||||
.get_proc_address(&CString::new(name).expect(name))
|
||||
},
|
||||
wgpu_types::GlBackendOptions::default(),
|
||||
)
|
||||
}
|
||||
.expect("GL adapter can't be initialized")
|
||||
});
|
||||
|
||||
window.request_redraw();
|
||||
self.state = Some((gl_context, gl_surface, window));
|
||||
}
|
||||
}
|
||||
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
let mut app = App::new();
|
||||
event_loop
|
||||
.run_app(&mut app)
|
||||
.expect("Couldn't run event loop");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "emscripten")]
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
|
||||
println!("Initializing external GL context");
|
||||
let egl = khronos_egl::Instance::new(khronos_egl::Static);
|
||||
let display = unsafe { egl.get_display(khronos_egl::DEFAULT_DISPLAY) }.unwrap();
|
||||
egl.initialize(display)
|
||||
.expect("unable to initialize display");
|
||||
|
||||
let attributes = [
|
||||
khronos_egl::RED_SIZE,
|
||||
8,
|
||||
khronos_egl::GREEN_SIZE,
|
||||
8,
|
||||
khronos_egl::BLUE_SIZE,
|
||||
8,
|
||||
khronos_egl::NONE,
|
||||
];
|
||||
|
||||
let config = egl
|
||||
.choose_first_config(display, &attributes)
|
||||
.unwrap()
|
||||
.expect("unable to choose config");
|
||||
let surface = unsafe {
|
||||
let window = std::ptr::null_mut::<std::ffi::c_void>();
|
||||
egl.create_window_surface(display, config, window, None)
|
||||
}
|
||||
.expect("unable to create surface");
|
||||
|
||||
let context_attributes = [khronos_egl::CONTEXT_CLIENT_VERSION, 3, khronos_egl::NONE];
|
||||
|
||||
let gl_context = egl
|
||||
.create_context(display, config, None, &context_attributes)
|
||||
.expect("unable to create context");
|
||||
egl.make_current(display, Some(surface), Some(surface), Some(gl_context))
|
||||
.expect("can't make context current");
|
||||
|
||||
println!("Hooking up to wgpu-hal");
|
||||
let exposed = unsafe {
|
||||
<hal::api::Gles as hal::Api>::Adapter::new_external(|name| {
|
||||
egl.get_proc_address(name)
|
||||
.map_or(std::ptr::null(), |p| p as *const _)
|
||||
})
|
||||
}
|
||||
.expect("GL adapter can't be initialized");
|
||||
|
||||
fill_screen(&exposed, 640, 400);
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
all(target_arch = "wasm32", not(target_os = "emscripten")),
|
||||
target_os = "ios",
|
||||
target_os = "visionos",
|
||||
target_env = "ohos"
|
||||
))]
|
||||
fn main() {
|
||||
eprintln!("This example is not supported on this platform")
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
all(target_arch = "wasm32", not(target_os = "emscripten")),
|
||||
target_os = "ios",
|
||||
target_os = "visionos"
|
||||
)))]
|
||||
fn fill_screen(exposed: &hal::ExposedAdapter<hal::api::Gles>, width: u32, height: u32) {
|
||||
use hal::{Adapter as _, CommandEncoder as _, Device as _, Queue as _};
|
||||
|
||||
let od = unsafe {
|
||||
exposed.adapter.open(
|
||||
wgpu_types::Features::empty(),
|
||||
&wgpu_types::Limits::downlevel_defaults(),
|
||||
&wgpu_types::MemoryHints::default(),
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
|
||||
let format = wgpu_types::TextureFormat::Rgba8UnormSrgb;
|
||||
let texture = <hal::api::Gles as hal::Api>::Texture::default_framebuffer(format);
|
||||
let view = unsafe {
|
||||
od.device
|
||||
.create_texture_view(
|
||||
&texture,
|
||||
&hal::TextureViewDescriptor {
|
||||
label: None,
|
||||
format,
|
||||
dimension: wgpu_types::TextureViewDimension::D2,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
println!("Filling the screen");
|
||||
let mut encoder = unsafe {
|
||||
od.device
|
||||
.create_command_encoder(&hal::CommandEncoderDescriptor {
|
||||
label: None,
|
||||
queue: &od.queue,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let mut fence = unsafe { od.device.create_fence().unwrap() };
|
||||
let rp_desc = hal::RenderPassDescriptor {
|
||||
label: None,
|
||||
extent: wgpu_types::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
sample_count: 1,
|
||||
color_attachments: &[Some(hal::ColorAttachment {
|
||||
target: hal::Attachment {
|
||||
view: &view,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
},
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: hal::AttachmentOps::STORE | hal::AttachmentOps::LOAD_CLEAR,
|
||||
clear_value: wgpu_types::Color::BLUE,
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
multiview_mask: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
};
|
||||
unsafe {
|
||||
encoder.begin_encoding(None).unwrap();
|
||||
encoder.begin_render_pass(&rp_desc).unwrap();
|
||||
encoder.end_render_pass();
|
||||
let cmd_buf = encoder.end_encoding().unwrap();
|
||||
od.queue.submit(&[&cmd_buf], &[], (&mut fence, 0)).unwrap();
|
||||
}
|
||||
}
|
||||
+1225
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,39 @@
|
||||
enable wgpu_ray_query;
|
||||
|
||||
struct Uniforms {
|
||||
view_inv: mat4x4<f32>,
|
||||
proj_inv: mat4x4<f32>,
|
||||
};
|
||||
@group(0) @binding(0)
|
||||
var<uniform> uniforms: Uniforms;
|
||||
|
||||
@group(0) @binding(1)
|
||||
var output: texture_storage_2d<rgba8unorm, write>;
|
||||
|
||||
@group(0) @binding(2)
|
||||
var acc_struct: acceleration_structure;
|
||||
|
||||
@compute @workgroup_size(8, 8)
|
||||
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
|
||||
let target_size = textureDimensions(output);
|
||||
|
||||
let pixel_center = vec2<f32>(global_id.xy) + vec2<f32>(0.5);
|
||||
let in_uv = pixel_center / vec2<f32>(target_size.xy);
|
||||
let d = in_uv * 2.0 - 1.0;
|
||||
|
||||
let origin = (uniforms.view_inv * vec4<f32>(0.0, 0.0, 0.0, 1.0)).xyz;
|
||||
let temp = uniforms.proj_inv * vec4<f32>(d.x, d.y, 1.0, 1.0);
|
||||
let direction = (uniforms.view_inv * vec4<f32>(normalize(temp.xyz), 0.0)).xyz;
|
||||
|
||||
var rq: ray_query;
|
||||
rayQueryInitialize(&rq, acc_struct, RayDesc(0u, 0xFFu, 0.1, 200.0, origin, direction));
|
||||
rayQueryProceed(&rq);
|
||||
|
||||
var color = vec4<f32>(0.0, 0.0, 0.0, 1.0);
|
||||
let intersection = rayQueryGetCommittedIntersection(&rq);
|
||||
if intersection.kind != RAY_QUERY_INTERSECTION_NONE {
|
||||
color = vec4<f32>(intersection.barycentrics, 1.0 - intersection.barycentrics.x - intersection.barycentrics.y, 1.0);
|
||||
}
|
||||
|
||||
textureStore(output, global_id.xy, color);
|
||||
}
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
use alloc::string::String;
|
||||
use std::{ffi::OsString, os::windows::ffi::OsStringExt};
|
||||
|
||||
use windows::Win32::Graphics::Dxgi;
|
||||
|
||||
// Helper to convert DXGI adapter name to a normal string
|
||||
pub fn map_adapter_name(name: [u16; 128]) -> String {
|
||||
let len = name.iter().take_while(|&&c| c != 0).count();
|
||||
let name = OsString::from_wide(&name[..len]);
|
||||
name.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
pub fn map_texture_format_failable(
|
||||
format: wgt::TextureFormat,
|
||||
) -> Option<Dxgi::Common::DXGI_FORMAT> {
|
||||
use wgt::TextureFormat as Tf;
|
||||
use Dxgi::Common::*;
|
||||
|
||||
Some(match format {
|
||||
Tf::R8Unorm => DXGI_FORMAT_R8_UNORM,
|
||||
Tf::R8Snorm => DXGI_FORMAT_R8_SNORM,
|
||||
Tf::R8Uint => DXGI_FORMAT_R8_UINT,
|
||||
Tf::R8Sint => DXGI_FORMAT_R8_SINT,
|
||||
Tf::R16Uint => DXGI_FORMAT_R16_UINT,
|
||||
Tf::R16Sint => DXGI_FORMAT_R16_SINT,
|
||||
Tf::R16Unorm => DXGI_FORMAT_R16_UNORM,
|
||||
Tf::R16Snorm => DXGI_FORMAT_R16_SNORM,
|
||||
Tf::R16Float => DXGI_FORMAT_R16_FLOAT,
|
||||
Tf::Rg8Unorm => DXGI_FORMAT_R8G8_UNORM,
|
||||
Tf::Rg8Snorm => DXGI_FORMAT_R8G8_SNORM,
|
||||
Tf::Rg8Uint => DXGI_FORMAT_R8G8_UINT,
|
||||
Tf::Rg8Sint => DXGI_FORMAT_R8G8_SINT,
|
||||
Tf::Rg16Unorm => DXGI_FORMAT_R16G16_UNORM,
|
||||
Tf::Rg16Snorm => DXGI_FORMAT_R16G16_SNORM,
|
||||
Tf::R32Uint => DXGI_FORMAT_R32_UINT,
|
||||
Tf::R32Sint => DXGI_FORMAT_R32_SINT,
|
||||
Tf::R32Float => DXGI_FORMAT_R32_FLOAT,
|
||||
Tf::Rg16Uint => DXGI_FORMAT_R16G16_UINT,
|
||||
Tf::Rg16Sint => DXGI_FORMAT_R16G16_SINT,
|
||||
Tf::Rg16Float => DXGI_FORMAT_R16G16_FLOAT,
|
||||
Tf::Rgba8Unorm => DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
Tf::Rgba8UnormSrgb => DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
|
||||
Tf::Bgra8UnormSrgb => DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
|
||||
Tf::Rgba8Snorm => DXGI_FORMAT_R8G8B8A8_SNORM,
|
||||
Tf::Bgra8Unorm => DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
Tf::Rgba8Uint => DXGI_FORMAT_R8G8B8A8_UINT,
|
||||
Tf::Rgba8Sint => DXGI_FORMAT_R8G8B8A8_SINT,
|
||||
Tf::Rgb9e5Ufloat => DXGI_FORMAT_R9G9B9E5_SHAREDEXP,
|
||||
Tf::Rgb10a2Uint => DXGI_FORMAT_R10G10B10A2_UINT,
|
||||
Tf::Rgb10a2Unorm => DXGI_FORMAT_R10G10B10A2_UNORM,
|
||||
Tf::Rg11b10Ufloat => DXGI_FORMAT_R11G11B10_FLOAT,
|
||||
Tf::R64Uint => DXGI_FORMAT_R32G32_UINT, // R64 emulated by R32G32
|
||||
Tf::Rg32Uint => DXGI_FORMAT_R32G32_UINT,
|
||||
Tf::Rg32Sint => DXGI_FORMAT_R32G32_SINT,
|
||||
Tf::Rg32Float => DXGI_FORMAT_R32G32_FLOAT,
|
||||
Tf::Rgba16Uint => DXGI_FORMAT_R16G16B16A16_UINT,
|
||||
Tf::Rgba16Sint => DXGI_FORMAT_R16G16B16A16_SINT,
|
||||
Tf::Rgba16Unorm => DXGI_FORMAT_R16G16B16A16_UNORM,
|
||||
Tf::Rgba16Snorm => DXGI_FORMAT_R16G16B16A16_SNORM,
|
||||
Tf::Rgba16Float => DXGI_FORMAT_R16G16B16A16_FLOAT,
|
||||
Tf::Rgba32Uint => DXGI_FORMAT_R32G32B32A32_UINT,
|
||||
Tf::Rgba32Sint => DXGI_FORMAT_R32G32B32A32_SINT,
|
||||
Tf::Rgba32Float => DXGI_FORMAT_R32G32B32A32_FLOAT,
|
||||
Tf::Stencil8 => DXGI_FORMAT_D24_UNORM_S8_UINT,
|
||||
Tf::Depth16Unorm => DXGI_FORMAT_D16_UNORM,
|
||||
Tf::Depth24Plus => DXGI_FORMAT_D24_UNORM_S8_UINT,
|
||||
Tf::Depth24PlusStencil8 => DXGI_FORMAT_D24_UNORM_S8_UINT,
|
||||
Tf::Depth32Float => DXGI_FORMAT_D32_FLOAT,
|
||||
Tf::Depth32FloatStencil8 => DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
|
||||
Tf::NV12 => DXGI_FORMAT_NV12,
|
||||
Tf::P010 => DXGI_FORMAT_P010,
|
||||
Tf::Bc1RgbaUnorm => DXGI_FORMAT_BC1_UNORM,
|
||||
Tf::Bc1RgbaUnormSrgb => DXGI_FORMAT_BC1_UNORM_SRGB,
|
||||
Tf::Bc2RgbaUnorm => DXGI_FORMAT_BC2_UNORM,
|
||||
Tf::Bc2RgbaUnormSrgb => DXGI_FORMAT_BC2_UNORM_SRGB,
|
||||
Tf::Bc3RgbaUnorm => DXGI_FORMAT_BC3_UNORM,
|
||||
Tf::Bc3RgbaUnormSrgb => DXGI_FORMAT_BC3_UNORM_SRGB,
|
||||
Tf::Bc4RUnorm => DXGI_FORMAT_BC4_UNORM,
|
||||
Tf::Bc4RSnorm => DXGI_FORMAT_BC4_SNORM,
|
||||
Tf::Bc5RgUnorm => DXGI_FORMAT_BC5_UNORM,
|
||||
Tf::Bc5RgSnorm => DXGI_FORMAT_BC5_SNORM,
|
||||
Tf::Bc6hRgbUfloat => DXGI_FORMAT_BC6H_UF16,
|
||||
Tf::Bc6hRgbFloat => DXGI_FORMAT_BC6H_SF16,
|
||||
Tf::Bc7RgbaUnorm => DXGI_FORMAT_BC7_UNORM,
|
||||
Tf::Bc7RgbaUnormSrgb => DXGI_FORMAT_BC7_UNORM_SRGB,
|
||||
Tf::Etc2Rgb8Unorm
|
||||
| Tf::Etc2Rgb8UnormSrgb
|
||||
| Tf::Etc2Rgb8A1Unorm
|
||||
| Tf::Etc2Rgb8A1UnormSrgb
|
||||
| Tf::Etc2Rgba8Unorm
|
||||
| Tf::Etc2Rgba8UnormSrgb
|
||||
| Tf::EacR11Unorm
|
||||
| Tf::EacR11Snorm
|
||||
| Tf::EacRg11Unorm
|
||||
| Tf::EacRg11Snorm
|
||||
| Tf::Astc {
|
||||
block: _,
|
||||
channel: _,
|
||||
} => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn map_texture_format(format: wgt::TextureFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
match map_texture_format_failable(format) {
|
||||
Some(f) => f,
|
||||
None => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
// Note: DXGI doesn't allow sRGB format on the swapchain,
|
||||
// but creating RTV of swapchain buffers with sRGB works.
|
||||
pub fn map_texture_format_nosrgb(format: wgt::TextureFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
match format {
|
||||
wgt::TextureFormat::Bgra8UnormSrgb => Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
wgt::TextureFormat::Rgba8UnormSrgb => Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
_ => map_texture_format(format),
|
||||
}
|
||||
}
|
||||
|
||||
// SRV and UAV can't use the depth or typeless formats
|
||||
// see https://microsoft.github.io/DirectX-Specs/d3d/PlanarDepthStencilDDISpec.html#view-creation
|
||||
pub fn map_texture_format_for_srv_uav(
|
||||
format: wgt::TextureFormat,
|
||||
aspect: crate::FormatAspects,
|
||||
) -> Option<Dxgi::Common::DXGI_FORMAT> {
|
||||
Some(match (format, aspect) {
|
||||
(wgt::TextureFormat::Depth16Unorm, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R16_UNORM
|
||||
}
|
||||
(wgt::TextureFormat::Depth32Float, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R32_FLOAT
|
||||
}
|
||||
(wgt::TextureFormat::Depth32FloatStencil8, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS
|
||||
}
|
||||
(
|
||||
wgt::TextureFormat::Depth24Plus | wgt::TextureFormat::Depth24PlusStencil8,
|
||||
crate::FormatAspects::DEPTH,
|
||||
) => Dxgi::Common::DXGI_FORMAT_R24_UNORM_X8_TYPELESS,
|
||||
|
||||
(wgt::TextureFormat::Depth32FloatStencil8, crate::FormatAspects::STENCIL) => {
|
||||
Dxgi::Common::DXGI_FORMAT_X32_TYPELESS_G8X24_UINT
|
||||
}
|
||||
(
|
||||
wgt::TextureFormat::Stencil8 | wgt::TextureFormat::Depth24PlusStencil8,
|
||||
crate::FormatAspects::STENCIL,
|
||||
) => Dxgi::Common::DXGI_FORMAT_X24_TYPELESS_G8_UINT,
|
||||
|
||||
(_, crate::FormatAspects::DEPTH)
|
||||
| (_, crate::FormatAspects::STENCIL)
|
||||
| (_, crate::FormatAspects::DEPTH_STENCIL) => return None,
|
||||
|
||||
_ => map_texture_format(format),
|
||||
})
|
||||
}
|
||||
|
||||
// see https://microsoft.github.io/DirectX-Specs/d3d/PlanarDepthStencilDDISpec.html#planar-layout-for-staging-from-buffer
|
||||
pub fn map_texture_format_for_copy(
|
||||
format: wgt::TextureFormat,
|
||||
aspect: crate::FormatAspects,
|
||||
) -> Option<Dxgi::Common::DXGI_FORMAT> {
|
||||
Some(match (format, aspect) {
|
||||
(wgt::TextureFormat::Depth16Unorm, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R16_UNORM
|
||||
}
|
||||
(
|
||||
wgt::TextureFormat::Depth32Float | wgt::TextureFormat::Depth32FloatStencil8,
|
||||
crate::FormatAspects::DEPTH,
|
||||
) => Dxgi::Common::DXGI_FORMAT_R32_FLOAT,
|
||||
|
||||
(
|
||||
wgt::TextureFormat::Stencil8
|
||||
| wgt::TextureFormat::Depth24PlusStencil8
|
||||
| wgt::TextureFormat::Depth32FloatStencil8,
|
||||
crate::FormatAspects::STENCIL,
|
||||
) => Dxgi::Common::DXGI_FORMAT_R8_UINT,
|
||||
|
||||
// `CopyTextureRegion` on a plane subresource wants the
|
||||
// single-plane DXGI format, not the planar one.
|
||||
(format, aspects) if format.is_multi_planar_format() && aspects.is_one() => {
|
||||
map_texture_format(format.aspect_specific_format(aspects.map())?)
|
||||
}
|
||||
|
||||
(format, crate::FormatAspects::COLOR) => map_texture_format(format),
|
||||
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn map_texture_format_for_resource(
|
||||
format: wgt::TextureFormat,
|
||||
usage: wgt::TextureUses,
|
||||
has_view_formats: bool,
|
||||
casting_fully_typed_format_supported: bool,
|
||||
) -> Dxgi::Common::DXGI_FORMAT {
|
||||
use wgt::TextureFormat as Tf;
|
||||
use Dxgi::Common::*;
|
||||
|
||||
if casting_fully_typed_format_supported {
|
||||
map_texture_format(format)
|
||||
|
||||
// We might view this resource as srgb or non-srgb
|
||||
} else if has_view_formats {
|
||||
match format {
|
||||
Tf::Rgba8Unorm | Tf::Rgba8UnormSrgb => DXGI_FORMAT_R8G8B8A8_TYPELESS,
|
||||
Tf::Bgra8Unorm | Tf::Bgra8UnormSrgb => DXGI_FORMAT_B8G8R8A8_TYPELESS,
|
||||
Tf::Bc1RgbaUnorm | Tf::Bc1RgbaUnormSrgb => DXGI_FORMAT_BC1_TYPELESS,
|
||||
Tf::Bc2RgbaUnorm | Tf::Bc2RgbaUnormSrgb => DXGI_FORMAT_BC2_TYPELESS,
|
||||
Tf::Bc3RgbaUnorm | Tf::Bc3RgbaUnormSrgb => DXGI_FORMAT_BC3_TYPELESS,
|
||||
Tf::Bc7RgbaUnorm | Tf::Bc7RgbaUnormSrgb => DXGI_FORMAT_BC7_TYPELESS,
|
||||
format => map_texture_format(format),
|
||||
}
|
||||
|
||||
// We might view this resource as SRV/UAV but also as DSV
|
||||
} else if format.is_depth_stencil_format()
|
||||
&& usage.intersects(
|
||||
wgt::TextureUses::RESOURCE
|
||||
| wgt::TextureUses::STORAGE_READ_ONLY
|
||||
| wgt::TextureUses::STORAGE_WRITE_ONLY
|
||||
| wgt::TextureUses::STORAGE_READ_WRITE,
|
||||
)
|
||||
{
|
||||
match format {
|
||||
Tf::Depth16Unorm => DXGI_FORMAT_R16_TYPELESS,
|
||||
Tf::Depth32Float => DXGI_FORMAT_R32_TYPELESS,
|
||||
Tf::Depth32FloatStencil8 => DXGI_FORMAT_R32G8X24_TYPELESS,
|
||||
Tf::Stencil8 | Tf::Depth24Plus | Tf::Depth24PlusStencil8 => DXGI_FORMAT_R24G8_TYPELESS,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
} else {
|
||||
map_texture_format(format)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_index_format(format: wgt::IndexFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
match format {
|
||||
wgt::IndexFormat::Uint16 => Dxgi::Common::DXGI_FORMAT_R16_UINT,
|
||||
wgt::IndexFormat::Uint32 => Dxgi::Common::DXGI_FORMAT_R32_UINT,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_vertex_format(format: wgt::VertexFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
use wgt::VertexFormat as Vf;
|
||||
use Dxgi::Common::*;
|
||||
|
||||
match format {
|
||||
Vf::Unorm8 => DXGI_FORMAT_R8_UNORM,
|
||||
Vf::Snorm8 => DXGI_FORMAT_R8_SNORM,
|
||||
Vf::Uint8 => DXGI_FORMAT_R8_UINT,
|
||||
Vf::Sint8 => DXGI_FORMAT_R8_SINT,
|
||||
Vf::Unorm8x2 => DXGI_FORMAT_R8G8_UNORM,
|
||||
Vf::Snorm8x2 => DXGI_FORMAT_R8G8_SNORM,
|
||||
Vf::Uint8x2 => DXGI_FORMAT_R8G8_UINT,
|
||||
Vf::Sint8x2 => DXGI_FORMAT_R8G8_SINT,
|
||||
Vf::Unorm8x4 => DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
Vf::Snorm8x4 => DXGI_FORMAT_R8G8B8A8_SNORM,
|
||||
Vf::Uint8x4 => DXGI_FORMAT_R8G8B8A8_UINT,
|
||||
Vf::Sint8x4 => DXGI_FORMAT_R8G8B8A8_SINT,
|
||||
Vf::Unorm16 => DXGI_FORMAT_R16_UNORM,
|
||||
Vf::Snorm16 => DXGI_FORMAT_R16_SNORM,
|
||||
Vf::Uint16 => DXGI_FORMAT_R16_UINT,
|
||||
Vf::Sint16 => DXGI_FORMAT_R16_SINT,
|
||||
Vf::Float16 => DXGI_FORMAT_R16_FLOAT,
|
||||
Vf::Unorm16x2 => DXGI_FORMAT_R16G16_UNORM,
|
||||
Vf::Snorm16x2 => DXGI_FORMAT_R16G16_SNORM,
|
||||
Vf::Uint16x2 => DXGI_FORMAT_R16G16_UINT,
|
||||
Vf::Sint16x2 => DXGI_FORMAT_R16G16_SINT,
|
||||
Vf::Float16x2 => DXGI_FORMAT_R16G16_FLOAT,
|
||||
Vf::Unorm16x4 => DXGI_FORMAT_R16G16B16A16_UNORM,
|
||||
Vf::Snorm16x4 => DXGI_FORMAT_R16G16B16A16_SNORM,
|
||||
Vf::Uint16x4 => DXGI_FORMAT_R16G16B16A16_UINT,
|
||||
Vf::Sint16x4 => DXGI_FORMAT_R16G16B16A16_SINT,
|
||||
Vf::Float16x4 => DXGI_FORMAT_R16G16B16A16_FLOAT,
|
||||
Vf::Uint32 => DXGI_FORMAT_R32_UINT,
|
||||
Vf::Sint32 => DXGI_FORMAT_R32_SINT,
|
||||
Vf::Float32 => DXGI_FORMAT_R32_FLOAT,
|
||||
Vf::Uint32x2 => DXGI_FORMAT_R32G32_UINT,
|
||||
Vf::Sint32x2 => DXGI_FORMAT_R32G32_SINT,
|
||||
Vf::Float32x2 => DXGI_FORMAT_R32G32_FLOAT,
|
||||
Vf::Uint32x3 => DXGI_FORMAT_R32G32B32_UINT,
|
||||
Vf::Sint32x3 => DXGI_FORMAT_R32G32B32_SINT,
|
||||
Vf::Float32x3 => DXGI_FORMAT_R32G32B32_FLOAT,
|
||||
Vf::Uint32x4 => DXGI_FORMAT_R32G32B32A32_UINT,
|
||||
Vf::Sint32x4 => DXGI_FORMAT_R32G32B32A32_SINT,
|
||||
Vf::Float32x4 => DXGI_FORMAT_R32G32B32A32_FLOAT,
|
||||
Vf::Unorm10_10_10_2 => DXGI_FORMAT_R10G10B10A2_UNORM,
|
||||
Vf::Unorm8x4Bgra => DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
Vf::Float64 | Vf::Float64x2 | Vf::Float64x3 | Vf::Float64x4 => unimplemented!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_acomposite_alpha_mode(mode: wgt::CompositeAlphaMode) -> Dxgi::Common::DXGI_ALPHA_MODE {
|
||||
match mode {
|
||||
wgt::CompositeAlphaMode::PreMultiplied => Dxgi::Common::DXGI_ALPHA_MODE_PREMULTIPLIED,
|
||||
wgt::CompositeAlphaMode::PostMultiplied => Dxgi::Common::DXGI_ALPHA_MODE_STRAIGHT,
|
||||
wgt::CompositeAlphaMode::Opaque => Dxgi::Common::DXGI_ALPHA_MODE_IGNORE,
|
||||
wgt::CompositeAlphaMode::Auto | wgt::CompositeAlphaMode::Inherit => {
|
||||
Dxgi::Common::DXGI_ALPHA_MODE_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
use alloc::{borrow::Cow, string::String};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use windows::Win32::{Foundation, System::Diagnostics::Debug};
|
||||
|
||||
// This is a mutex as opposed to an atomic as we need to completely
|
||||
// lock everyone out until we have registered or unregistered the
|
||||
// exception handler, otherwise really nasty races could happen.
|
||||
//
|
||||
// By routing all the registration through these functions we can guarantee
|
||||
// there is either 1 or 0 exception handlers registered, not multiple.
|
||||
static EXCEPTION_HANDLER_COUNT: Mutex<usize> = Mutex::new(0);
|
||||
|
||||
pub fn register_exception_handler() {
|
||||
let mut count_guard = EXCEPTION_HANDLER_COUNT.lock();
|
||||
if *count_guard == 0 {
|
||||
unsafe { Debug::AddVectoredExceptionHandler(0, Some(output_debug_string_handler)) };
|
||||
}
|
||||
*count_guard += 1;
|
||||
}
|
||||
|
||||
pub fn unregister_exception_handler() {
|
||||
let mut count_guard = EXCEPTION_HANDLER_COUNT.lock();
|
||||
if *count_guard == 1 {
|
||||
unsafe { Debug::RemoveVectoredExceptionHandler(output_debug_string_handler as *mut _) };
|
||||
}
|
||||
*count_guard -= 1;
|
||||
}
|
||||
|
||||
const MESSAGE_PREFIXES: &[(&str, log::Level)] = &[
|
||||
("CORRUPTION", log::Level::Error),
|
||||
("ERROR", log::Level::Error),
|
||||
("WARNING", log::Level::Warn),
|
||||
// We intentionally suppress "INFO" messages down to debug
|
||||
// so that users are not innundated with info messages from the runtime.
|
||||
("INFO", log::Level::Debug),
|
||||
("MESSAGE", log::Level::Trace),
|
||||
];
|
||||
|
||||
unsafe extern "system" fn output_debug_string_handler(
|
||||
exception_info: *mut Debug::EXCEPTION_POINTERS,
|
||||
) -> i32 {
|
||||
// See https://stackoverflow.com/a/41480827
|
||||
let record = unsafe { &*(*exception_info).ExceptionRecord };
|
||||
if record.NumberParameters != 2 {
|
||||
return Debug::EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
let message = match record.ExceptionCode {
|
||||
Foundation::DBG_PRINTEXCEPTION_C => {
|
||||
String::from_utf8_lossy(bytemuck::cast_slice(&record.ExceptionInformation))
|
||||
}
|
||||
Foundation::DBG_PRINTEXCEPTION_WIDE_C => Cow::Owned(String::from_utf16_lossy(
|
||||
bytemuck::cast_slice(&record.ExceptionInformation),
|
||||
)),
|
||||
_ => return Debug::EXCEPTION_CONTINUE_SEARCH,
|
||||
};
|
||||
|
||||
let message = match message.strip_prefix("D3D12 ") {
|
||||
Some(msg) => msg
|
||||
.trim_end_matches("\n\0")
|
||||
.trim_end_matches("[ STATE_CREATION WARNING #0: UNKNOWN]"),
|
||||
None => return Debug::EXCEPTION_CONTINUE_SEARCH,
|
||||
};
|
||||
|
||||
let (message, level) = match MESSAGE_PREFIXES
|
||||
.iter()
|
||||
.find(|&&(prefix, _)| message.starts_with(prefix))
|
||||
{
|
||||
Some(&(prefix, level)) => (&message[prefix.len() + 2..], level),
|
||||
None => (message, log::Level::Debug),
|
||||
};
|
||||
|
||||
if level == log::Level::Warn && message.contains("#82") {
|
||||
// This is are useless spammy warnings (#820, #821):
|
||||
// "The application did not pass any clear value to resource creation"
|
||||
return Debug::EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
if level == log::Level::Warn && message.contains("DRAW_EMPTY_SCISSOR_RECTANGLE") {
|
||||
// This is normal, WebGPU allows passing empty scissor rectangles.
|
||||
return Debug::EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
let _ = std::panic::catch_unwind(|| {
|
||||
log::log!(level, "{message}");
|
||||
});
|
||||
|
||||
#[cfg(feature = "validation_canary")]
|
||||
if cfg!(debug_assertions) && level == log::Level::Error {
|
||||
use alloc::string::ToString as _;
|
||||
|
||||
// Set canary and continue
|
||||
crate::VALIDATION_CANARY.add(message.to_string());
|
||||
}
|
||||
|
||||
Debug::EXCEPTION_CONTINUE_EXECUTION
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
use alloc::{string::String, vec::Vec};
|
||||
use core::ops::Deref;
|
||||
|
||||
use windows::{core::Interface as _, Win32::Graphics::Dxgi};
|
||||
|
||||
use crate::dx12::DxgiLib;
|
||||
|
||||
use super::result::HResult as _;
|
||||
|
||||
// We can rely on the presence of DXGI 1.4 since D3D12 requires WDDM 2.0, Windows 10 (1507), and so does DXGI 1.4.
|
||||
|
||||
fn should_keep_adapter(adapter: &Dxgi::IDXGIAdapter1) -> bool {
|
||||
let desc = unsafe { adapter.GetDesc1() }.unwrap();
|
||||
|
||||
// The Intel Haswell family of iGPUs had support for the D3D12 API but it was later
|
||||
// removed due to a security vulnerability.
|
||||
//
|
||||
// We are explicitly filtering out all the devices in the family because we are now
|
||||
// getting reports of device loss at a later time than at device creation time (`D3D12CreateDevice`).
|
||||
//
|
||||
// See https://www.intel.com/content/www/us/en/support/articles/000057520/graphics.html
|
||||
// This list of device IDs is from https://dgpu-docs.intel.com/devices/hardware-table.html
|
||||
let haswell_device_ids = [
|
||||
0x0422, 0x0426, 0x042A, 0x042B, 0x042E, 0x0C22, 0x0C26, 0x0C2A, 0x0C2B, 0x0C2E, 0x0A22,
|
||||
0x0A2A, 0x0A2B, 0x0D2A, 0x0D2B, 0x0D2E, 0x0A26, 0x0A2E, 0x0D22, 0x0D26, 0x0412, 0x0416,
|
||||
0x0D12, 0x041A, 0x041B, 0x0C12, 0x0C16, 0x0C1A, 0x0C1B, 0x0C1E, 0x0A12, 0x0A1A, 0x0A1B,
|
||||
0x0D16, 0x0D1A, 0x0D1B, 0x0D1E, 0x041E, 0x0A16, 0x0A1E, 0x0402, 0x0406, 0x040A, 0x040B,
|
||||
0x040E, 0x0C02, 0x0C06, 0x0C0A, 0x0C0B, 0x0C0E, 0x0A02, 0x0A06, 0x0A0A, 0x0A0B, 0x0A0E,
|
||||
0x0D02, 0x0D06, 0x0D0A, 0x0D0B, 0x0D0E,
|
||||
];
|
||||
if desc.VendorId == 0x8086 && haswell_device_ids.contains(&desc.DeviceId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If run completely headless, windows will show two different WARP adapters, one
|
||||
// which is lying about being an integrated card. This is so that programs
|
||||
// that ignore software adapters will actually run on headless/gpu-less machines.
|
||||
//
|
||||
// We don't want that and discourage that kind of filtering anyway, so we skip the integrated WARP.
|
||||
if desc.VendorId == 5140
|
||||
&& !Dxgi::DXGI_ADAPTER_FLAG(desc.Flags as i32).contains(Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE)
|
||||
{
|
||||
let adapter_name = super::conv::map_adapter_name(desc.Description);
|
||||
if adapter_name.contains("Microsoft Basic Render Driver") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum DxgiAdapter {
|
||||
/// Provided by DXGI 1.4
|
||||
Adapter3(Dxgi::IDXGIAdapter3),
|
||||
/// Provided by DXGI 1.6
|
||||
Adapter4(Dxgi::IDXGIAdapter4),
|
||||
}
|
||||
|
||||
impl DxgiAdapter {
|
||||
pub fn query_video_memory_info(
|
||||
&self,
|
||||
group: Dxgi::DXGI_MEMORY_SEGMENT_GROUP,
|
||||
) -> Result<Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO, crate::DeviceError> {
|
||||
let mut info = Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO::default();
|
||||
unsafe { self.QueryVideoMemoryInfo(0, group, &mut info) }
|
||||
.into_device_result("QueryVideoMemoryInfo")?;
|
||||
Ok(info)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for DxgiAdapter {
|
||||
type Target = Dxgi::IDXGIAdapter3;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match self {
|
||||
DxgiAdapter::Adapter3(a) => a,
|
||||
DxgiAdapter::Adapter4(a) => a,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enumerate_adapters(factory: DxgiFactory) -> Vec<DxgiAdapter> {
|
||||
let mut adapters = Vec::with_capacity(8);
|
||||
|
||||
for cur_index in 0.. {
|
||||
profiling::scope!("IDXGIFactory1::EnumAdapters1");
|
||||
let adapter1: Dxgi::IDXGIAdapter1 = match unsafe { factory.EnumAdapters1(cur_index) } {
|
||||
Ok(a) => a,
|
||||
Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break,
|
||||
Err(e) => {
|
||||
log::error!("Failed enumerating adapters: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
if !should_keep_adapter(&adapter1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Ok(adapter4) = adapter1.cast::<Dxgi::IDXGIAdapter4>() {
|
||||
adapters.push(DxgiAdapter::Adapter4(adapter4));
|
||||
} else {
|
||||
let adapter3 = adapter1.cast::<Dxgi::IDXGIAdapter3>().unwrap();
|
||||
adapters.push(DxgiAdapter::Adapter3(adapter3));
|
||||
}
|
||||
}
|
||||
|
||||
adapters
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum DxgiFactory {
|
||||
/// Provided by DXGI 1.4
|
||||
Factory4(Dxgi::IDXGIFactory4),
|
||||
/// Provided by DXGI 1.5
|
||||
Factory5(Dxgi::IDXGIFactory5),
|
||||
/// Provided by DXGI 1.6
|
||||
Factory6(Dxgi::IDXGIFactory6),
|
||||
}
|
||||
|
||||
impl Deref for DxgiFactory {
|
||||
type Target = Dxgi::IDXGIFactory4;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match self {
|
||||
DxgiFactory::Factory4(f) => f,
|
||||
DxgiFactory::Factory5(f) => f,
|
||||
DxgiFactory::Factory6(f) => f,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DxgiFactory {
|
||||
pub fn as_factory5(&self) -> Option<&Dxgi::IDXGIFactory5> {
|
||||
match self {
|
||||
Self::Factory4(_) => None,
|
||||
Self::Factory5(f) => Some(f),
|
||||
Self::Factory6(f) => Some(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_factory(
|
||||
instance_flags: wgt::InstanceFlags,
|
||||
) -> Result<(DxgiLib, DxgiFactory), crate::InstanceError> {
|
||||
let lib_dxgi = DxgiLib::new().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("failed to load dxgi.dll"), e)
|
||||
})?;
|
||||
|
||||
let mut factory_flags = Dxgi::DXGI_CREATE_FACTORY_FLAGS::default();
|
||||
|
||||
if instance_flags.contains(wgt::InstanceFlags::VALIDATION) {
|
||||
// The `DXGI_CREATE_FACTORY_DEBUG` flag is only allowed to be passed to
|
||||
// `CreateDXGIFactory2` if the debug interface is actually available. So
|
||||
// we check for whether it exists first.
|
||||
if let Ok(Some(_)) = lib_dxgi.debug_interface1() {
|
||||
factory_flags |= Dxgi::DXGI_CREATE_FACTORY_DEBUG;
|
||||
}
|
||||
}
|
||||
|
||||
let factory4 = match lib_dxgi.create_factory4(factory_flags) {
|
||||
Ok(factory) => factory,
|
||||
Err(err) => {
|
||||
return Err(crate::InstanceError::with_source(
|
||||
String::from("IDXGIFactory4 creation failed"),
|
||||
err,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if let Ok(factory6) = factory4.cast::<Dxgi::IDXGIFactory6>() {
|
||||
return Ok((lib_dxgi, DxgiFactory::Factory6(factory6)));
|
||||
}
|
||||
|
||||
if let Ok(factory5) = factory4.cast::<Dxgi::IDXGIFactory5>() {
|
||||
return Ok((lib_dxgi, DxgiFactory::Factory5(factory5)));
|
||||
}
|
||||
|
||||
Ok((lib_dxgi, DxgiFactory::Factory4(factory4)))
|
||||
}
|
||||
+352
@@ -0,0 +1,352 @@
|
||||
//! Reading a window's [`wgt::DisplayHdrInfo`] through DXGI.
|
||||
//!
|
||||
//! Lives in `auxil/dxgi` so the DX12 and Vulkan-on-Windows backends share it:
|
||||
//! both query through a [`DxgiHdrSource`], so the same monitor reports identical
|
||||
//! numbers under either backend.
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use windows::{
|
||||
core::Interface as _,
|
||||
Win32::{
|
||||
Foundation::HWND,
|
||||
Graphics::{Dxgi, Gdi},
|
||||
},
|
||||
};
|
||||
|
||||
/// The primary colors of a color space, in CIE 1931 xy:
|
||||
/// `[[red_x, red_y], [green_x, green_y], [blue_x, blue_y]]`.
|
||||
type Primaries = [[f32; 2]; 3];
|
||||
|
||||
/// Reference primaries (CIE 1931 xy: red, green, blue) for the three coarse
|
||||
/// gamut buckets, used to classify a display's reported primaries.
|
||||
const REC709: Primaries = [[0.640, 0.330], [0.300, 0.600], [0.150, 0.060]];
|
||||
const DISPLAY_P3: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060]];
|
||||
const REC2020: Primaries = [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]];
|
||||
|
||||
/// Classifies reported primaries into the closest coarse [`wgt::DisplayGamut`]
|
||||
/// bucket (least-squares over the R/G/B chromaticities). Advisory only.
|
||||
///
|
||||
/// Returns `None` if every primary is zeroed (the EDID reported nothing usable),
|
||||
/// so a bogus all-zero descriptor is not misclassified as sRGB.
|
||||
fn classify_gamut(red: [f32; 2], green: [f32; 2], blue: [f32; 2]) -> Option<wgt::DisplayGamut> {
|
||||
let measured = [red, green, blue];
|
||||
if measured.iter().all(|p| p[0] == 0.0 && p[1] == 0.0) {
|
||||
return None;
|
||||
}
|
||||
let dist = |reference: &Primaries| -> f32 {
|
||||
measured
|
||||
.iter()
|
||||
.zip(reference)
|
||||
.map(|(m, r)| {
|
||||
let dx = m[0] - r[0];
|
||||
let dy = m[1] - r[1];
|
||||
dx * dx + dy * dy
|
||||
})
|
||||
.sum()
|
||||
};
|
||||
[
|
||||
(wgt::DisplayGamut::Srgb, dist(&REC709)),
|
||||
(wgt::DisplayGamut::DisplayP3, dist(&DISPLAY_P3)),
|
||||
(wgt::DisplayGamut::Rec2020, dist(&REC2020)),
|
||||
]
|
||||
.into_iter()
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(gamut, _)| gamut)
|
||||
}
|
||||
|
||||
/// Maps an [`IDXGIOutput6::GetDesc1`] result and the SDR white level (from
|
||||
/// [`sdr_white_nits_for_monitor`]) into the backend-agnostic
|
||||
/// [`wgt::DisplayHdrInfo`].
|
||||
///
|
||||
/// Pure: it interprets `desc1` without any system call. Numeric values are
|
||||
/// advisory (EDID-sourced); see [`wgt::DisplayLuminance`].
|
||||
///
|
||||
/// [`IDXGIOutput6::GetDesc1`]: windows::Win32::Graphics::Dxgi::IDXGIOutput6::GetDesc1
|
||||
fn display_hdr_info_from_desc1(
|
||||
desc1: &Dxgi::DXGI_OUTPUT_DESC1,
|
||||
sdr_white_nits: Option<f32>,
|
||||
) -> wgt::DisplayHdrInfo {
|
||||
// The output is in an HDR color space if its `ColorSpace` is one of the two
|
||||
// Windows uses for HDR swap-chains: HDR10 / PQ (`G2084_NONE_P2020`) or
|
||||
// scRGB / linear-extended-sRGB (`G10_NONE_P709`). Checking both ensures scRGB
|
||||
// HDR is not misreported as SDR.
|
||||
let high_dynamic_range = desc1.ColorSpace
|
||||
== Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020
|
||||
|| desc1.ColorSpace == Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709;
|
||||
|
||||
let luminance = wgt::DisplayLuminance {
|
||||
max_nits: Some(desc1.MaxLuminance),
|
||||
max_full_frame_nits: Some(desc1.MaxFullFrameLuminance),
|
||||
min_nits: Some(desc1.MinLuminance),
|
||||
sdr_white_nits,
|
||||
};
|
||||
|
||||
let chromaticity = wgt::DisplayChromaticity {
|
||||
red: Some(desc1.RedPrimary),
|
||||
green: Some(desc1.GreenPrimary),
|
||||
blue: Some(desc1.BluePrimary),
|
||||
white: Some(desc1.WhitePoint),
|
||||
};
|
||||
|
||||
let coarse = wgt::DisplayCoarseRange {
|
||||
high_dynamic_range: Some(high_dynamic_range),
|
||||
gamut: classify_gamut(desc1.RedPrimary, desc1.GreenPrimary, desc1.BluePrimary),
|
||||
};
|
||||
|
||||
// `headroom` is `None`: DXGI exposes absolute luminance (captured in
|
||||
// `luminance`) rather than a relative headroom ratio. `bits_per_color` drops
|
||||
// values that don't fit `u8`.
|
||||
wgt::DisplayHdrInfo {
|
||||
luminance: Some(luminance),
|
||||
headroom: None,
|
||||
chromaticity: Some(chromaticity),
|
||||
coarse: Some(coarse),
|
||||
bits_per_color: u8::try_from(desc1.BitsPerColor).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A window's display HDR info, read through DXGI.
|
||||
///
|
||||
/// Bundles the window's `HWND` with the DXGI factory used to query it. The factory
|
||||
/// is built once and reused, rebuilt only when DXGI reports it stale; the monitor
|
||||
/// lookup and adapter/output walk still run every call, since the window can move
|
||||
/// between displays and the SDR white level changes at runtime.
|
||||
pub struct DxgiHdrSource {
|
||||
hwnd: HWND,
|
||||
factory: Mutex<Option<Dxgi::IDXGIFactory1>>,
|
||||
}
|
||||
|
||||
// SAFETY: `HWND` and `IDXGIFactory1` are `!Send`/`!Sync` in windows-rs. The `HWND`
|
||||
// is only ever read to run a DXGI query (fine from any thread), and the factory is
|
||||
// free-threaded for the enumeration done here with the `Mutex` serializing access.
|
||||
// This mirrors the manual `Send`/`Sync` on `dx12::Surface`.
|
||||
unsafe impl Send for DxgiHdrSource {}
|
||||
unsafe impl Sync for DxgiHdrSource {}
|
||||
|
||||
impl DxgiHdrSource {
|
||||
/// Creates a source for the window identified by `hwnd`. The `HWND` is
|
||||
/// borrowed; using the source after that window is destroyed is undefined
|
||||
/// behavior.
|
||||
pub fn new(hwnd: HWND) -> Self {
|
||||
Self {
|
||||
hwnd,
|
||||
factory: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the window's [`wgt::DisplayHdrInfo`], or `None` if its monitor can't
|
||||
/// be identified or queried (a headless or composition window, a
|
||||
/// pre-Win10-1703 system without `IDXGIOutput6`, or a COM failure). Never
|
||||
/// panics.
|
||||
pub fn display_hdr_info(&self) -> Option<wgt::DisplayHdrInfo> {
|
||||
let desc1 = self.output_desc1()?;
|
||||
let sdr_white_nits = sdr_white_nits_for_monitor(desc1.Monitor);
|
||||
Some(display_hdr_info_from_desc1(&desc1, sdr_white_nits))
|
||||
}
|
||||
|
||||
/// The [`DXGI_OUTPUT_DESC1`] for the window's monitor, reusing the cached
|
||||
/// factory unless DXGI reports it stale.
|
||||
///
|
||||
/// [`DXGI_OUTPUT_DESC1`]: Dxgi::DXGI_OUTPUT_DESC1
|
||||
fn output_desc1(&self) -> Option<Dxgi::DXGI_OUTPUT_DESC1> {
|
||||
let mut factory = self.factory.lock();
|
||||
|
||||
// A factory only enumerates the adapter/output topology it saw at
|
||||
// creation, so rebuild it once it reports `IsCurrent() == false` (a
|
||||
// monitor or GPU was plugged or unplugged).
|
||||
// SAFETY: a cached factory is live; `IsCurrent` takes no caller pointers.
|
||||
let need_new = factory
|
||||
.as_ref()
|
||||
.is_none_or(|f| !unsafe { f.IsCurrent() }.as_bool());
|
||||
if need_new {
|
||||
// SAFETY: `CreateDXGIFactory1` takes no caller pointers; the `windows`
|
||||
// binding fills the interface out-pointer itself.
|
||||
match unsafe { Dxgi::CreateDXGIFactory1() } {
|
||||
Ok(new) => *factory = Some(new),
|
||||
Err(e) => {
|
||||
log::warn!("CreateDXGIFactory1 failed: {e}");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
output_desc1_from_factory(factory.as_ref()?, self.hwnd)
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`DXGI_OUTPUT_DESC1`] for the monitor backing `wnd_handle`, found by
|
||||
/// walking every adapter's outputs on `factory` — not just the rendering
|
||||
/// adapter's, so the monitor is found on hybrid-GPU systems where the window sits
|
||||
/// on a display wired to a different adapter. `None` if none match.
|
||||
///
|
||||
/// [`DXGI_OUTPUT_DESC1`]: Dxgi::DXGI_OUTPUT_DESC1
|
||||
fn output_desc1_from_factory(
|
||||
factory: &Dxgi::IDXGIFactory1,
|
||||
wnd_handle: HWND,
|
||||
) -> Option<Dxgi::DXGI_OUTPUT_DESC1> {
|
||||
// SAFETY: `MonitorFromWindow` is sound for any `HWND`; an invalid one yields
|
||||
// a null `HMONITOR`, checked below.
|
||||
let hmonitor = unsafe { Gdi::MonitorFromWindow(wnd_handle, Gdi::MONITOR_DEFAULTTONEAREST) };
|
||||
if hmonitor.is_invalid() {
|
||||
log::warn!("MonitorFromWindow failed; cannot identify the window's output");
|
||||
return None;
|
||||
}
|
||||
for adapter_index in 0.. {
|
||||
// SAFETY: `factory` is live; `EnumAdapters1` takes only an index.
|
||||
let adapter = match unsafe { factory.EnumAdapters1(adapter_index) } {
|
||||
Ok(adapter) => adapter,
|
||||
// End of the adapter list: the monitor matched none of them.
|
||||
Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break,
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIFactory1::EnumAdapters1 failed: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
for output_index in 0.. {
|
||||
// SAFETY: `adapter` is live (from above); `EnumOutputs` takes only
|
||||
// an index.
|
||||
let output = match unsafe { adapter.EnumOutputs(output_index) } {
|
||||
Ok(output) => output,
|
||||
// End of this adapter's outputs: move on to the next adapter.
|
||||
Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break,
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIAdapter1::EnumOutputs failed: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
// SAFETY: `output` is live (from above); `GetDesc` returns a
|
||||
// binding-owned `DXGI_OUTPUT_DESC` by value.
|
||||
let desc = match unsafe { output.GetDesc() } {
|
||||
Ok(desc) => desc,
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIOutput::GetDesc failed: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if desc.Monitor != hmonitor {
|
||||
continue;
|
||||
}
|
||||
// The window's monitor matched, so a failure past this point is a
|
||||
// real anomaly. `IDXGIOutput6` (DXGI 1.6 / Win10 1703+) is required
|
||||
// for `GetDesc1`.
|
||||
let output6 = match output.cast::<Dxgi::IDXGIOutput6>() {
|
||||
Ok(output6) => output6,
|
||||
Err(e) => {
|
||||
log::warn!("Casting to IDXGIOutput6 failed: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// SAFETY: `output6` is live (from the cast above); `GetDesc1`
|
||||
// returns a binding-owned `DXGI_OUTPUT_DESC1` by value.
|
||||
return match unsafe { output6.GetDesc1() } {
|
||||
Ok(desc1) => Some(desc1),
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIOutput6::GetDesc1 failed: {e}");
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
log::warn!("No DXGI output matches the window's monitor");
|
||||
None
|
||||
}
|
||||
|
||||
/// Best-effort SDR white level in nits for `hmonitor`, via the Windows
|
||||
/// DisplayConfig API. Tracks the brightness slider, so it changes at runtime.
|
||||
///
|
||||
/// This is the only [`wgt::DisplayLuminance`] field `GetDesc1` doesn't carry; it
|
||||
/// bridges absolute nits and relative headroom. It lives in
|
||||
/// `DISPLAYCONFIG_SDR_WHITE_LEVEL`, outside DXGI, so it needs its own query.
|
||||
///
|
||||
/// Returns `None` on any failure (no match, query error, or a `0` reading). Never
|
||||
/// panics. Pass [`Dxgi::DXGI_OUTPUT_DESC1::Monitor`] so the value matches the rest
|
||||
/// of the `DisplayHdrInfo`.
|
||||
fn sdr_white_nits_for_monitor(hmonitor: Gdi::HMONITOR) -> Option<f32> {
|
||||
use windows::Win32::{
|
||||
Devices::Display::{
|
||||
DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QueryDisplayConfig,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_MODE_INFO,
|
||||
DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SDR_WHITE_LEVEL,
|
||||
DISPLAYCONFIG_SOURCE_DEVICE_NAME, QDC_ONLY_ACTIVE_PATHS,
|
||||
},
|
||||
Foundation::ERROR_SUCCESS,
|
||||
Graphics::Gdi::{GetMonitorInfoW, MONITORINFO, MONITORINFOEXW},
|
||||
};
|
||||
|
||||
// 1. HMONITOR -> GDI device name (e.g. `\\.\DISPLAY1`).
|
||||
let mut monitor_info = MONITORINFOEXW::default();
|
||||
monitor_info.monitorInfo.cbSize = size_of::<MONITORINFOEXW>() as u32;
|
||||
// `GetMonitorInfoW` takes a `*mut MONITORINFO`; the `EXW` variant is
|
||||
// layout-compatible (it starts with `MONITORINFO`) and reports `cbSize`.
|
||||
let lpmi = core::ptr::from_mut(&mut monitor_info).cast::<MONITORINFO>();
|
||||
// SAFETY: `lpmi` points at a live `MONITORINFOEXW` with `cbSize` set, which
|
||||
// bounds the write; an invalid `hmonitor` just fails (handled below).
|
||||
let got_info = unsafe { GetMonitorInfoW(hmonitor, lpmi) };
|
||||
if !got_info.as_bool() {
|
||||
return None;
|
||||
}
|
||||
let gdi_device_name = monitor_info.szDevice;
|
||||
|
||||
// 2. Enumerate the active DisplayConfig paths.
|
||||
let mut path_count = 0u32;
|
||||
let mut mode_count = 0u32;
|
||||
// SAFETY: both out-params are live `u32`s; the call only writes the required
|
||||
// buffer sizes into them.
|
||||
if unsafe {
|
||||
GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut path_count, &mut mode_count)
|
||||
} != ERROR_SUCCESS
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut paths = alloc::vec![DISPLAYCONFIG_PATH_INFO::default(); path_count as usize];
|
||||
let mut modes = alloc::vec![DISPLAYCONFIG_MODE_INFO::default(); mode_count as usize];
|
||||
// SAFETY: `paths`/`modes` are sized to the counts reported above and passed
|
||||
// with those counts, bounding the writes.
|
||||
if unsafe {
|
||||
QueryDisplayConfig(
|
||||
QDC_ONLY_ACTIVE_PATHS,
|
||||
&mut path_count,
|
||||
paths.as_mut_ptr(),
|
||||
&mut mode_count,
|
||||
modes.as_mut_ptr(),
|
||||
None,
|
||||
)
|
||||
} != ERROR_SUCCESS
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
// 3. Match the path whose source is this monitor, then read its target's
|
||||
// SDR white level. `DisplayConfigGetDeviceInfo` returns a WIN32 code as
|
||||
// `i32` (`0` == `ERROR_SUCCESS`).
|
||||
for path in paths.iter().take(path_count as usize) {
|
||||
let mut source = DISPLAYCONFIG_SOURCE_DEVICE_NAME::default();
|
||||
source.header.r#type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
|
||||
source.header.size = size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32;
|
||||
source.header.adapterId = path.sourceInfo.adapterId;
|
||||
source.header.id = path.sourceInfo.id;
|
||||
// SAFETY: `source` is live with `header.type`/`header.size` set, which
|
||||
// bounds the call's access to that struct.
|
||||
if unsafe { DisplayConfigGetDeviceInfo(&mut source.header) } != ERROR_SUCCESS.0 as i32 {
|
||||
continue;
|
||||
}
|
||||
if source.viewGdiDeviceName != gdi_device_name {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut white = DISPLAYCONFIG_SDR_WHITE_LEVEL::default();
|
||||
white.header.r#type = DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL;
|
||||
white.header.size = size_of::<DISPLAYCONFIG_SDR_WHITE_LEVEL>() as u32;
|
||||
white.header.adapterId = path.targetInfo.adapterId;
|
||||
white.header.id = path.targetInfo.id;
|
||||
// SAFETY: `white` is live with `header.type`/`header.size` set, which
|
||||
// bounds the call's access to that struct.
|
||||
if unsafe { DisplayConfigGetDeviceInfo(&mut white.header) } != ERROR_SUCCESS.0 as i32 {
|
||||
return None;
|
||||
}
|
||||
// `SDRWhiteLevel` encodes nits as `(nits / 80) * 1000`; `0` means the OS
|
||||
// reported nothing usable.
|
||||
return (white.SDRWhiteLevel > 0).then(|| white.SDRWhiteLevel as f32 * 80.0 / 1000.0);
|
||||
}
|
||||
None
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// Every module here is gated behind `dx12` except `hdr` (the
|
||||
// `DXGI_OUTPUT_DESC1` -> `DisplayHdrInfo` mapping), which the
|
||||
// Vulkan-on-Windows backend also uses.
|
||||
#[cfg(dx12)]
|
||||
pub mod conv;
|
||||
#[cfg(dx12)]
|
||||
pub mod exception;
|
||||
#[cfg(dx12)]
|
||||
pub mod factory;
|
||||
pub mod hdr;
|
||||
#[cfg(dx12)]
|
||||
pub mod name;
|
||||
#[cfg(dx12)]
|
||||
pub mod result;
|
||||
#[cfg(dx12)]
|
||||
pub mod time;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
use windows::Win32::Graphics::Direct3D12::ID3D12Object;
|
||||
|
||||
use crate::auxil::dxgi::result::HResult;
|
||||
|
||||
/// Helper trait for setting the name of a D3D12 object.
|
||||
///
|
||||
/// This is implemented on all types that can be converted to an [`ID3D12Object`].
|
||||
pub trait ObjectExt {
|
||||
fn set_name(&self, name: &str) -> Result<(), crate::DeviceError>;
|
||||
}
|
||||
|
||||
impl<T> ObjectExt for T
|
||||
where
|
||||
// Windows impls `From` for all parent interfaces, so we can use that to convert to ID3D12Object.
|
||||
//
|
||||
// This includes implementations for references.
|
||||
for<'a> &'a ID3D12Object: From<&'a T>,
|
||||
{
|
||||
fn set_name(&self, name: &str) -> Result<(), crate::DeviceError> {
|
||||
let name = windows::core::HSTRING::from(name);
|
||||
let object: &ID3D12Object = self.into();
|
||||
unsafe { object.SetName(&name).into_device_result("SetName") }
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
use windows::Win32::{Foundation, Graphics::Dxgi};
|
||||
|
||||
pub(crate) trait HResult<O> {
|
||||
fn into_device_result(self, description: &str) -> Result<O, crate::DeviceError>;
|
||||
}
|
||||
impl<T> HResult<T> for windows::core::Result<T> {
|
||||
fn into_device_result(self, description: &str) -> Result<T, crate::DeviceError> {
|
||||
#![allow(unreachable_code)]
|
||||
|
||||
self.map_err(|err| {
|
||||
log::error!("{description} failed: {err}");
|
||||
|
||||
match err.code() {
|
||||
Foundation::E_OUTOFMEMORY => crate::DeviceError::OutOfMemory,
|
||||
Dxgi::DXGI_ERROR_DEVICE_RESET | Dxgi::DXGI_ERROR_DEVICE_REMOVED => {
|
||||
#[cfg(feature = "device_lost_panic")]
|
||||
panic!("{description} failed: Device lost ({err})");
|
||||
crate::DeviceError::Lost
|
||||
}
|
||||
_ => {
|
||||
#[cfg(feature = "internal_error_panic")]
|
||||
panic!("{description} failed: {err}");
|
||||
crate::DeviceError::Unexpected
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
#![allow(dead_code, reason = "IPresentationManager is unused currently")]
|
||||
|
||||
use windows::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency};
|
||||
|
||||
pub enum PresentationTimer {
|
||||
/// DXGI uses [`QueryPerformanceCounter()`]
|
||||
Dxgi {
|
||||
/// How many ticks of QPC per second
|
||||
frequency: u64,
|
||||
},
|
||||
/// [`IPresentationManager`] uses [`QueryInterruptTimePrecise()`]
|
||||
///
|
||||
/// [`IPresentationManager`]: https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Graphics/CompositionSwapchain/struct.IPresentationManager.html
|
||||
/// [`QueryInterruptTimePrecise()`]: https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/System/WindowsProgramming/fn.QueryInterruptTimePrecise.html
|
||||
#[allow(non_snake_case)]
|
||||
IPresentationManager {
|
||||
fnQueryInterruptTimePrecise: unsafe extern "system" fn(*mut u64),
|
||||
},
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for PresentationTimer {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match *self {
|
||||
Self::Dxgi { frequency } => f
|
||||
.debug_struct("DXGI")
|
||||
.field("frequency", &frequency)
|
||||
.finish(),
|
||||
Self::IPresentationManager {
|
||||
fnQueryInterruptTimePrecise,
|
||||
} => f
|
||||
.debug_struct("IPresentationManager")
|
||||
.field(
|
||||
"QueryInterruptTimePrecise",
|
||||
&(fnQueryInterruptTimePrecise as usize),
|
||||
)
|
||||
.finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PresentationTimer {
|
||||
/// Create a presentation timer using QueryPerformanceFrequency (what DXGI uses for presentation times)
|
||||
pub fn new_dxgi() -> Self {
|
||||
let mut frequency = 0;
|
||||
unsafe { QueryPerformanceFrequency(&mut frequency) }.unwrap();
|
||||
|
||||
Self::Dxgi {
|
||||
frequency: frequency
|
||||
.try_into()
|
||||
.expect("Frequency should not be negative"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a presentation timer using QueryInterruptTimePrecise (what IPresentationManager uses for presentation times)
|
||||
///
|
||||
/// Panics if QueryInterruptTimePrecise isn't found (below Win10)
|
||||
pub fn new_ipresentation_manager() -> Self {
|
||||
// We need to load this explicitly, as QueryInterruptTimePrecise is only available on Windows 10+
|
||||
//
|
||||
// Docs say it's in kernel32.dll, but it's actually in kernelbase.dll.
|
||||
// api-ms-win-core-realtime-l1-1-1.dll
|
||||
let kernelbase =
|
||||
libloading::os::windows::Library::open_already_loaded("kernelbase.dll").unwrap();
|
||||
// No concerns about lifetimes here as kernelbase is always there.
|
||||
let ptr = unsafe {
|
||||
kernelbase
|
||||
.get(c"QueryInterruptTimePrecise".to_bytes())
|
||||
.unwrap()
|
||||
};
|
||||
Self::IPresentationManager {
|
||||
fnQueryInterruptTimePrecise: *ptr,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the current time in nanoseconds.
|
||||
pub fn get_timestamp_ns(&self) -> u128 {
|
||||
// Always do u128 math _after_ hitting the timing function.
|
||||
match *self {
|
||||
PresentationTimer::Dxgi { frequency } => {
|
||||
let mut counter = 0;
|
||||
unsafe { QueryPerformanceCounter(&mut counter) }.unwrap();
|
||||
|
||||
// counter * (1_000_000_000 / freq) but re-ordered to make more precise
|
||||
(counter as u128 * 1_000_000_000) / frequency as u128
|
||||
}
|
||||
PresentationTimer::IPresentationManager {
|
||||
fnQueryInterruptTimePrecise,
|
||||
} => {
|
||||
let mut counter = 0;
|
||||
unsafe { fnQueryInterruptTimePrecise(&mut counter) };
|
||||
|
||||
// QueryInterruptTimePrecise uses units of 100ns for its tick.
|
||||
counter as u128 * 100
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+241
@@ -0,0 +1,241 @@
|
||||
// Mostly DX12-only, but also compiled for Vulkan-on-Windows, which reuses
|
||||
// `dxgi::hdr` to query display HDR info. The DX12-only submodules stay gated
|
||||
// behind `dx12` in `dxgi/mod.rs`.
|
||||
#[cfg(any(dx12, all(vulkan, windows)))]
|
||||
pub(super) mod dxgi;
|
||||
|
||||
#[cfg(all(native, feature = "renderdoc"))]
|
||||
pub(super) mod renderdoc;
|
||||
|
||||
pub mod db {
|
||||
pub mod amd {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x1002;
|
||||
}
|
||||
pub mod apple {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x106B;
|
||||
}
|
||||
pub mod arm {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x13B5;
|
||||
}
|
||||
pub mod broadcom {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x14E4;
|
||||
}
|
||||
pub mod imgtec {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x1010;
|
||||
}
|
||||
pub mod intel {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x8086;
|
||||
pub const DEVICE_KABY_LAKE_MASK: u32 = 0x5900;
|
||||
pub const DEVICE_SKY_LAKE_MASK: u32 = 0x1900;
|
||||
}
|
||||
pub mod mesa {
|
||||
// Mesa does not actually have a PCI vendor id.
|
||||
//
|
||||
// To match Vulkan, we use the VkVendorId for Mesa in the gles backend so that lavapipe (Vulkan) and
|
||||
// llvmpipe (OpenGL) have the same vendor id.
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x10005;
|
||||
}
|
||||
pub mod nvidia {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x10DE;
|
||||
}
|
||||
pub mod qualcomm {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x5143;
|
||||
}
|
||||
}
|
||||
|
||||
/// Maximum binding size for the shaders that only support `i32` indexing.
|
||||
/// Interestingly, the index itself can't reach that high, because the minimum
|
||||
/// element size is 4 bytes, but the compiler toolchain still computes the
|
||||
/// offset at some intermediate point, internally, as i32.
|
||||
pub const MAX_I32_BINDING_SIZE: u32 = (1 << 31) - 1;
|
||||
|
||||
pub use wgpu_naga_bridge::map_naga_stage;
|
||||
|
||||
impl crate::CopyExtent {
|
||||
pub fn map_extent_to_copy_size(extent: &wgt::Extent3d, dim: wgt::TextureDimension) -> Self {
|
||||
Self {
|
||||
width: extent.width,
|
||||
height: extent.height,
|
||||
depth: match dim {
|
||||
wgt::TextureDimension::D1 | wgt::TextureDimension::D2 => 1,
|
||||
wgt::TextureDimension::D3 => extent.depth_or_array_layers,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn min(&self, other: &Self) -> Self {
|
||||
Self {
|
||||
width: self.width.min(other.width),
|
||||
height: self.height.min(other.height),
|
||||
depth: self.depth.min(other.depth),
|
||||
}
|
||||
}
|
||||
|
||||
// Get the copy size at a specific mipmap level. This doesn't make most sense,
|
||||
// since the copy extents are provided *for* a mipmap level to start with.
|
||||
// But backends use `CopyExtent` more sparingly, and this piece is shared.
|
||||
pub fn at_mip_level(&self, level: u32) -> Self {
|
||||
Self {
|
||||
width: (self.width >> level).max(1),
|
||||
height: (self.height >> level).max(1),
|
||||
depth: (self.depth >> level).max(1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::TextureCopyBase {
|
||||
pub fn max_copy_size(&self, full_size: &crate::CopyExtent) -> crate::CopyExtent {
|
||||
let mip = full_size.at_mip_level(self.mip_level);
|
||||
crate::CopyExtent {
|
||||
width: mip.width - self.origin.x,
|
||||
height: mip.height - self.origin.y,
|
||||
depth: mip.depth - self.origin.z,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::BufferTextureCopy {
|
||||
pub fn clamp_size_to_virtual(&mut self, full_size: &crate::CopyExtent) {
|
||||
let max_size = self.texture_base.max_copy_size(full_size);
|
||||
self.size = self.size.min(&max_size);
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::TextureCopy {
|
||||
pub fn clamp_size_to_virtual(
|
||||
&mut self,
|
||||
full_src_size: &crate::CopyExtent,
|
||||
full_dst_size: &crate::CopyExtent,
|
||||
) {
|
||||
let max_src_size = self.src_base.max_copy_size(full_src_size);
|
||||
let max_dst_size = self.dst_base.max_copy_size(full_dst_size);
|
||||
self.size = self.size.min(&max_src_size).min(&max_dst_size);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adjust `limits` to honor HAL-imposed maximums and comply with WebGPU's
|
||||
/// adapter capability guarantees.
|
||||
#[cfg_attr(not(any_backend), allow(dead_code))]
|
||||
pub(crate) fn adjust_raw_limits(mut limits: wgt::Limits) -> wgt::Limits {
|
||||
// Apply hal limits.
|
||||
limits.max_bind_groups = limits.max_bind_groups.min(crate::MAX_BIND_GROUPS as u32);
|
||||
limits.max_vertex_buffers = limits
|
||||
.max_vertex_buffers
|
||||
.min(crate::MAX_VERTEX_BUFFERS as u32);
|
||||
// Once we allow the 2 limits above to be higher than 24 we should use
|
||||
// `cap_limits_to_be_under_the_sum_limit` to cap them under
|
||||
// `max_bind_groups_plus_vertex_buffers`.
|
||||
const { assert!(crate::MAX_BIND_GROUPS + crate::MAX_VERTEX_BUFFERS == 24) };
|
||||
limits.max_bind_groups_plus_vertex_buffers = limits.max_bind_groups_plus_vertex_buffers.min(24);
|
||||
limits.max_color_attachments = limits
|
||||
.max_color_attachments
|
||||
.min(crate::MAX_COLOR_ATTACHMENTS as u32);
|
||||
|
||||
// Adjust limits according to WebGPU adapter capability guarantees.
|
||||
// See <https://gpuweb.github.io/gpuweb/#adapter-capability-guarantees>.
|
||||
|
||||
// WebGPU requires maxBindingsPerBindGroup to be at least the sum of all
|
||||
// per-stage limits multiplied with the maximum shader stages per pipeline.
|
||||
//
|
||||
// Since backends already report their maximum maxBindingsPerBindGroup,
|
||||
// we need to lower all per-stage limits to satisfy this guarantee.
|
||||
const MAX_SHADER_STAGES_PER_PIPELINE: u32 = 2;
|
||||
let max_per_stage_resources =
|
||||
limits.max_bindings_per_bind_group / MAX_SHADER_STAGES_PER_PIPELINE;
|
||||
|
||||
cap_limits_to_be_under_the_sum_limit(
|
||||
[
|
||||
&mut limits.max_sampled_textures_per_shader_stage,
|
||||
&mut limits.max_uniform_buffers_per_shader_stage,
|
||||
&mut limits.max_storage_textures_per_shader_stage,
|
||||
&mut limits.max_storage_buffers_per_shader_stage,
|
||||
&mut limits.max_samplers_per_shader_stage,
|
||||
&mut limits.max_acceleration_structures_per_shader_stage,
|
||||
],
|
||||
max_per_stage_resources,
|
||||
);
|
||||
|
||||
// Not required by the spec but dynamic buffers count
|
||||
// towards non-dynamic buffer limits as well.
|
||||
limits.max_dynamic_uniform_buffers_per_pipeline_layout = limits
|
||||
.max_dynamic_uniform_buffers_per_pipeline_layout
|
||||
.min(limits.max_uniform_buffers_per_shader_stage);
|
||||
limits.max_dynamic_storage_buffers_per_pipeline_layout = limits
|
||||
.max_dynamic_storage_buffers_per_pipeline_layout
|
||||
.min(limits.max_storage_buffers_per_shader_stage);
|
||||
|
||||
limits.min_uniform_buffer_offset_alignment = limits.min_uniform_buffer_offset_alignment.max(32);
|
||||
limits.min_storage_buffer_offset_alignment = limits.min_storage_buffer_offset_alignment.max(32);
|
||||
|
||||
limits.max_uniform_buffer_binding_size = limits
|
||||
.max_uniform_buffer_binding_size
|
||||
.min(limits.max_buffer_size);
|
||||
limits.max_storage_buffer_binding_size = limits
|
||||
.max_storage_buffer_binding_size
|
||||
.min(limits.max_buffer_size);
|
||||
|
||||
limits.max_storage_buffer_binding_size &= !(u64::from(wgt::STORAGE_BINDING_SIZE_ALIGNMENT) - 1);
|
||||
limits.max_vertex_buffer_array_stride &= !(wgt::VERTEX_ALIGNMENT as u32 - 1);
|
||||
|
||||
let x = limits.max_compute_workgroup_size_x;
|
||||
let y = limits.max_compute_workgroup_size_y;
|
||||
let z = limits.max_compute_workgroup_size_z;
|
||||
let m = limits.max_compute_invocations_per_workgroup;
|
||||
limits.max_compute_workgroup_size_x = x.min(m);
|
||||
limits.max_compute_workgroup_size_y = y.min(m);
|
||||
limits.max_compute_workgroup_size_z = z.min(m);
|
||||
limits.max_compute_invocations_per_workgroup = m.min(x.saturating_mul(y).saturating_mul(z));
|
||||
|
||||
limits.max_immediate_size = limits.max_immediate_size.min(256);
|
||||
|
||||
limits
|
||||
}
|
||||
|
||||
/// Evenly allocates space to each limit,
|
||||
/// capping them only if strictly necessary.
|
||||
pub fn cap_limits_to_be_under_the_sum_limit<const N: usize>(
|
||||
mut limits: [&mut u32; N],
|
||||
sum_limit: u32,
|
||||
) {
|
||||
limits.sort();
|
||||
|
||||
let mut rem_limit = sum_limit;
|
||||
let mut divisor = limits.len() as u32;
|
||||
for limit_to_adjust in limits {
|
||||
let limit = rem_limit / divisor;
|
||||
*limit_to_adjust = (*limit_to_adjust).min(limit);
|
||||
rem_limit -= *limit_to_adjust;
|
||||
divisor -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_cap_limits_to_be_under_the_sum_limit() {
|
||||
test([3, 3, 3], 3, [1, 1, 1]);
|
||||
test([3, 2, 1], 3, [1, 1, 1]);
|
||||
test([1, 2, 3], 6, [1, 2, 3]);
|
||||
test([1, 2, 3], 3, [1, 1, 1]);
|
||||
test([1, 8, 100], 6, [1, 2, 3]);
|
||||
test([2, 80, 80], 6, [2, 2, 2]);
|
||||
test([2, 80, 80], 12, [2, 5, 5]);
|
||||
|
||||
#[track_caller]
|
||||
fn test<const N: usize>(mut input: [u32; N], limit: u32, output: [u32; N]) {
|
||||
cap_limits_to_be_under_the_sum_limit(input.each_mut(), limit);
|
||||
assert_eq!(input, output);
|
||||
}
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
//! RenderDoc integration - <https://renderdoc.org/>
|
||||
#![cfg_attr(not(any(feature = "gles", feature = "vulkan")), allow(dead_code))]
|
||||
|
||||
use alloc::format;
|
||||
use alloc::string::String;
|
||||
use core::{ffi, ptr};
|
||||
|
||||
/// The dynamically loaded RenderDoc API function table
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub struct RenderDocApi {
|
||||
api: renderdoc_sys::RENDERDOC_API_1_4_1,
|
||||
lib: libloading::Library,
|
||||
}
|
||||
|
||||
unsafe impl Send for RenderDocApi {}
|
||||
unsafe impl Sync for RenderDocApi {}
|
||||
|
||||
/// RenderDoc API type
|
||||
#[derive(Debug)]
|
||||
pub enum RenderDoc {
|
||||
/// RenderDoc functionality is available
|
||||
Available {
|
||||
/// RenderDoc API with function pointers
|
||||
api: RenderDocApi,
|
||||
},
|
||||
/// RenderDoc functionality is _not_ available
|
||||
NotAvailable {
|
||||
/// A description why renderdoc functionality is not available
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
// TODO: replace with libloading API once supported
|
||||
#[cfg(unix)]
|
||||
const RTLD_NOLOAD: i32 = 0x4;
|
||||
|
||||
impl RenderDoc {
|
||||
pub unsafe fn new() -> Self {
|
||||
type GetApiFn = unsafe extern "C" fn(version: u32, out: *mut *mut ffi::c_void) -> i32;
|
||||
|
||||
#[cfg(windows)]
|
||||
let renderdoc_filename = "renderdoc.dll";
|
||||
#[cfg(all(unix, not(target_os = "android")))]
|
||||
let renderdoc_filename = "librenderdoc.so";
|
||||
#[cfg(target_os = "android")]
|
||||
let renderdoc_filename = "libVkLayer_GLES_RenderDoc.so";
|
||||
|
||||
#[cfg(unix)]
|
||||
let renderdoc_result: Result<libloading::Library, libloading::Error> = unsafe {
|
||||
libloading::os::unix::Library::open(
|
||||
Some(renderdoc_filename),
|
||||
libloading::os::unix::RTLD_NOW | RTLD_NOLOAD,
|
||||
)
|
||||
}
|
||||
.map(|lib| lib.into());
|
||||
|
||||
#[cfg(windows)]
|
||||
let renderdoc_result: Result<libloading::Library, libloading::Error> =
|
||||
libloading::os::windows::Library::open_already_loaded(renderdoc_filename)
|
||||
.map(|lib| lib.into());
|
||||
|
||||
let renderdoc_lib = match renderdoc_result {
|
||||
Ok(lib) => lib,
|
||||
Err(e) => {
|
||||
return RenderDoc::NotAvailable {
|
||||
reason: format!(
|
||||
"Unable to load renderdoc library '{renderdoc_filename}': {e:?}"
|
||||
),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let get_api: libloading::Symbol<GetApiFn> =
|
||||
match unsafe { renderdoc_lib.get(c"RENDERDOC_GetAPI".to_bytes()) } {
|
||||
Ok(api) => api,
|
||||
Err(e) => {
|
||||
return RenderDoc::NotAvailable {
|
||||
reason: format!(
|
||||
"Unable to get RENDERDOC_GetAPI from renderdoc library '{renderdoc_filename}': {e:?}"
|
||||
),
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut obj = ptr::null_mut();
|
||||
match unsafe { get_api(10401, &mut obj) } {
|
||||
1 => RenderDoc::Available {
|
||||
api: RenderDocApi {
|
||||
api: unsafe { *obj.cast::<renderdoc_sys::RENDERDOC_API_1_4_1>() },
|
||||
lib: renderdoc_lib,
|
||||
},
|
||||
},
|
||||
return_value => RenderDoc::NotAvailable {
|
||||
reason: format!(
|
||||
"Unable to get API from renderdoc library '{renderdoc_filename}': {return_value}"
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RenderDoc {
|
||||
fn default() -> Self {
|
||||
if !cfg!(debug_assertions) {
|
||||
return RenderDoc::NotAvailable {
|
||||
reason: "RenderDoc support is only enabled with 'debug_assertions'".into(),
|
||||
};
|
||||
}
|
||||
unsafe { Self::new() }
|
||||
}
|
||||
}
|
||||
/// An implementation specific handle
|
||||
pub type Handle = *mut ffi::c_void;
|
||||
|
||||
impl RenderDoc {
|
||||
/// Start a RenderDoc frame capture
|
||||
pub unsafe fn start_frame_capture(&self, device_handle: Handle, window_handle: Handle) -> bool {
|
||||
match *self {
|
||||
Self::Available { api: ref entry } => {
|
||||
unsafe { entry.api.StartFrameCapture.unwrap()(device_handle, window_handle) };
|
||||
true
|
||||
}
|
||||
Self::NotAvailable { ref reason } => {
|
||||
log::warn!("Could not start RenderDoc frame capture: {reason}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// End a RenderDoc frame capture
|
||||
pub unsafe fn end_frame_capture(&self, device_handle: Handle, window_handle: Handle) {
|
||||
match *self {
|
||||
Self::Available { api: ref entry } => {
|
||||
unsafe { entry.api.EndFrameCapture.unwrap()(device_handle, window_handle) };
|
||||
}
|
||||
Self::NotAvailable { ref reason } => {
|
||||
log::warn!("Could not end RenderDoc frame capture: {reason}")
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Vendored
+1546
File diff suppressed because it is too large
Load Diff
Vendored
+1868
File diff suppressed because it is too large
Load Diff
Vendored
+467
@@ -0,0 +1,467 @@
|
||||
use windows::Win32::Graphics::{Direct3D, Direct3D12, Dxgi};
|
||||
|
||||
pub fn map_buffer_usage_to_resource_flags(
|
||||
usage: wgt::BufferUses,
|
||||
) -> Direct3D12::D3D12_RESOURCE_FLAGS {
|
||||
let mut flags = Direct3D12::D3D12_RESOURCE_FLAG_NONE;
|
||||
if usage.contains(wgt::BufferUses::STORAGE_READ_WRITE)
|
||||
|| usage.contains(wgt::BufferUses::ACCELERATION_STRUCTURE_QUERY)
|
||||
{
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
}
|
||||
flags
|
||||
}
|
||||
|
||||
pub fn map_buffer_descriptor(
|
||||
desc: &crate::BufferDescriptor<'_>,
|
||||
) -> Direct3D12::D3D12_RESOURCE_DESC {
|
||||
Direct3D12::D3D12_RESOURCE_DESC {
|
||||
Dimension: Direct3D12::D3D12_RESOURCE_DIMENSION_BUFFER,
|
||||
Alignment: 0,
|
||||
Width: desc.size,
|
||||
Height: 1,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN,
|
||||
SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
||||
Flags: map_buffer_usage_to_resource_flags(desc.usage),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_texture_dimension(dim: wgt::TextureDimension) -> Direct3D12::D3D12_RESOURCE_DIMENSION {
|
||||
match dim {
|
||||
wgt::TextureDimension::D1 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE1D,
|
||||
wgt::TextureDimension::D2 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE2D,
|
||||
wgt::TextureDimension::D3 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE3D,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_texture_usage_to_resource_flags(
|
||||
usage: wgt::TextureUses,
|
||||
) -> Direct3D12::D3D12_RESOURCE_FLAGS {
|
||||
let mut flags = Direct3D12::D3D12_RESOURCE_FLAG_NONE;
|
||||
|
||||
if usage.contains(wgt::TextureUses::COLOR_TARGET) {
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
}
|
||||
if usage
|
||||
.intersects(wgt::TextureUses::DEPTH_STENCIL_READ | wgt::TextureUses::DEPTH_STENCIL_WRITE)
|
||||
{
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
|
||||
if !usage.contains(wgt::TextureUses::RESOURCE) {
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE;
|
||||
}
|
||||
}
|
||||
if usage.intersects(
|
||||
wgt::TextureUses::STORAGE_READ_ONLY
|
||||
| wgt::TextureUses::STORAGE_WRITE_ONLY
|
||||
| wgt::TextureUses::STORAGE_READ_WRITE,
|
||||
) {
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
}
|
||||
|
||||
flags
|
||||
}
|
||||
|
||||
pub fn map_address_mode(mode: wgt::AddressMode) -> Direct3D12::D3D12_TEXTURE_ADDRESS_MODE {
|
||||
use wgt::AddressMode as Am;
|
||||
match mode {
|
||||
Am::Repeat => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_WRAP,
|
||||
Am::MirrorRepeat => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_MIRROR,
|
||||
Am::ClampToEdge => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
Am::ClampToBorder => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_BORDER,
|
||||
//Am::MirrorClamp => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_filter_mode(mode: wgt::FilterMode) -> Direct3D12::D3D12_FILTER_TYPE {
|
||||
match mode {
|
||||
wgt::FilterMode::Nearest => Direct3D12::D3D12_FILTER_TYPE_POINT,
|
||||
wgt::FilterMode::Linear => Direct3D12::D3D12_FILTER_TYPE_LINEAR,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_mipmap_filter_mode(mode: wgt::MipmapFilterMode) -> Direct3D12::D3D12_FILTER_TYPE {
|
||||
match mode {
|
||||
wgt::MipmapFilterMode::Nearest => Direct3D12::D3D12_FILTER_TYPE_POINT,
|
||||
wgt::MipmapFilterMode::Linear => Direct3D12::D3D12_FILTER_TYPE_LINEAR,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_comparison(func: wgt::CompareFunction) -> Direct3D12::D3D12_COMPARISON_FUNC {
|
||||
use wgt::CompareFunction as Cf;
|
||||
match func {
|
||||
Cf::Never => Direct3D12::D3D12_COMPARISON_FUNC_NEVER,
|
||||
Cf::Less => Direct3D12::D3D12_COMPARISON_FUNC_LESS,
|
||||
Cf::LessEqual => Direct3D12::D3D12_COMPARISON_FUNC_LESS_EQUAL,
|
||||
Cf::Equal => Direct3D12::D3D12_COMPARISON_FUNC_EQUAL,
|
||||
Cf::GreaterEqual => Direct3D12::D3D12_COMPARISON_FUNC_GREATER_EQUAL,
|
||||
Cf::Greater => Direct3D12::D3D12_COMPARISON_FUNC_GREATER,
|
||||
Cf::NotEqual => Direct3D12::D3D12_COMPARISON_FUNC_NOT_EQUAL,
|
||||
Cf::Always => Direct3D12::D3D12_COMPARISON_FUNC_ALWAYS,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_border_color(border_color: Option<wgt::SamplerBorderColor>) -> [f32; 4] {
|
||||
use wgt::SamplerBorderColor as Sbc;
|
||||
match border_color {
|
||||
Some(Sbc::TransparentBlack) | Some(Sbc::Zero) | None => [0.0; 4],
|
||||
Some(Sbc::OpaqueBlack) => [0.0, 0.0, 0.0, 1.0],
|
||||
Some(Sbc::OpaqueWhite) => [1.0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_visibility(visibility: wgt::ShaderStages) -> Direct3D12::D3D12_SHADER_VISIBILITY {
|
||||
match visibility {
|
||||
wgt::ShaderStages::VERTEX => Direct3D12::D3D12_SHADER_VISIBILITY_VERTEX,
|
||||
wgt::ShaderStages::FRAGMENT => Direct3D12::D3D12_SHADER_VISIBILITY_PIXEL,
|
||||
_ => Direct3D12::D3D12_SHADER_VISIBILITY_ALL,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_binding_type(ty: &wgt::BindingType) -> Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE {
|
||||
use wgt::BindingType as Bt;
|
||||
match *ty {
|
||||
Bt::Sampler { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
|
||||
Bt::Buffer {
|
||||
ty: wgt::BufferBindingType::Uniform,
|
||||
..
|
||||
} => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
|
||||
Bt::Buffer {
|
||||
ty: wgt::BufferBindingType::Storage { read_only: true },
|
||||
..
|
||||
}
|
||||
| Bt::Texture { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
|
||||
Bt::Buffer {
|
||||
ty: wgt::BufferBindingType::Storage { read_only: false },
|
||||
..
|
||||
}
|
||||
| Bt::StorageTexture { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
|
||||
Bt::AccelerationStructure { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
|
||||
// External textures require multiple bindings and therefore cannot
|
||||
// be mapped to a single descriptor range type. They must be handled
|
||||
// separately by the caller.
|
||||
Bt::ExternalTexture => unreachable!("External textures must be handled separately"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_buffer_usage_to_state(usage: wgt::BufferUses) -> Direct3D12::D3D12_RESOURCE_STATES {
|
||||
use wgt::BufferUses as Bu;
|
||||
let mut state = Direct3D12::D3D12_RESOURCE_STATE_COMMON;
|
||||
|
||||
if usage.intersects(Bu::COPY_SRC) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
}
|
||||
if usage.intersects(Bu::COPY_DST) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
}
|
||||
if usage.intersects(Bu::INDEX) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_INDEX_BUFFER;
|
||||
}
|
||||
if usage.intersects(Bu::VERTEX | Bu::UNIFORM) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
|
||||
}
|
||||
if usage.intersects(Bu::STORAGE_READ_WRITE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
} else if usage.intersects(Bu::STORAGE_READ_ONLY) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE
|
||||
| Direct3D12::D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
|
||||
}
|
||||
if usage.intersects(Bu::INDIRECT) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
|
||||
}
|
||||
if usage.intersects(Bu::ACCELERATION_STRUCTURE_QUERY) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
pub fn map_texture_usage_to_state(usage: wgt::TextureUses) -> Direct3D12::D3D12_RESOURCE_STATES {
|
||||
use wgt::TextureUses as Tu;
|
||||
let mut state = Direct3D12::D3D12_RESOURCE_STATE_COMMON;
|
||||
//Note: `RESOLVE_SOURCE` and `RESOLVE_DEST` are not used here
|
||||
//Note: `PRESENT` is the same as `COMMON`
|
||||
if usage == wgt::TextureUses::UNINITIALIZED {
|
||||
return state;
|
||||
}
|
||||
|
||||
if usage.intersects(Tu::COPY_SRC) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
}
|
||||
if usage.intersects(Tu::COPY_DST) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
}
|
||||
if usage.intersects(Tu::RESOURCE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE
|
||||
| Direct3D12::D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
|
||||
}
|
||||
if usage.intersects(Tu::COLOR_TARGET) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
}
|
||||
if usage.intersects(Tu::DEPTH_STENCIL_READ) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_DEPTH_READ;
|
||||
}
|
||||
if usage.intersects(Tu::DEPTH_STENCIL_WRITE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_DEPTH_WRITE;
|
||||
}
|
||||
if usage.intersects(Tu::STORAGE_READ_ONLY | Tu::STORAGE_WRITE_ONLY | Tu::STORAGE_READ_WRITE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
pub fn map_topology(
|
||||
topology: wgt::PrimitiveTopology,
|
||||
) -> (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY,
|
||||
) {
|
||||
match topology {
|
||||
wgt::PrimitiveTopology::PointList => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_POINTLIST,
|
||||
),
|
||||
wgt::PrimitiveTopology::LineList => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_LINELIST,
|
||||
),
|
||||
wgt::PrimitiveTopology::LineStrip => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_LINESTRIP,
|
||||
),
|
||||
wgt::PrimitiveTopology::TriangleList => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
|
||||
),
|
||||
wgt::PrimitiveTopology::TriangleStrip => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_polygon_mode(mode: wgt::PolygonMode) -> Direct3D12::D3D12_FILL_MODE {
|
||||
match mode {
|
||||
wgt::PolygonMode::Fill => Direct3D12::D3D12_FILL_MODE_SOLID,
|
||||
wgt::PolygonMode::Line => Direct3D12::D3D12_FILL_MODE_WIREFRAME,
|
||||
wgt::PolygonMode::Point => panic!(
|
||||
"{:?} is not enabled for this backend",
|
||||
wgt::Features::POLYGON_MODE_POINT
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// D3D12 doesn't support passing factors ending in `_COLOR` for alpha blending
|
||||
/// (see <https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_render_target_blend_desc>).
|
||||
/// Therefore this function takes an additional `is_alpha` argument
|
||||
/// which if set will return an equivalent `_ALPHA` factor.
|
||||
fn map_blend_factor(factor: wgt::BlendFactor, is_alpha: bool) -> Direct3D12::D3D12_BLEND {
|
||||
use wgt::BlendFactor as Bf;
|
||||
match factor {
|
||||
Bf::Zero => Direct3D12::D3D12_BLEND_ZERO,
|
||||
Bf::One => Direct3D12::D3D12_BLEND_ONE,
|
||||
Bf::Src if is_alpha => Direct3D12::D3D12_BLEND_SRC_ALPHA,
|
||||
Bf::Src => Direct3D12::D3D12_BLEND_SRC_COLOR,
|
||||
Bf::OneMinusSrc if is_alpha => Direct3D12::D3D12_BLEND_INV_SRC_ALPHA,
|
||||
Bf::OneMinusSrc => Direct3D12::D3D12_BLEND_INV_SRC_COLOR,
|
||||
Bf::Dst if is_alpha => Direct3D12::D3D12_BLEND_DEST_ALPHA,
|
||||
Bf::Dst => Direct3D12::D3D12_BLEND_DEST_COLOR,
|
||||
Bf::OneMinusDst if is_alpha => Direct3D12::D3D12_BLEND_INV_DEST_ALPHA,
|
||||
Bf::OneMinusDst => Direct3D12::D3D12_BLEND_INV_DEST_COLOR,
|
||||
Bf::SrcAlpha => Direct3D12::D3D12_BLEND_SRC_ALPHA,
|
||||
Bf::OneMinusSrcAlpha => Direct3D12::D3D12_BLEND_INV_SRC_ALPHA,
|
||||
Bf::DstAlpha => Direct3D12::D3D12_BLEND_DEST_ALPHA,
|
||||
Bf::OneMinusDstAlpha => Direct3D12::D3D12_BLEND_INV_DEST_ALPHA,
|
||||
Bf::Constant => Direct3D12::D3D12_BLEND_BLEND_FACTOR,
|
||||
Bf::OneMinusConstant => Direct3D12::D3D12_BLEND_INV_BLEND_FACTOR,
|
||||
Bf::SrcAlphaSaturated => Direct3D12::D3D12_BLEND_SRC_ALPHA_SAT,
|
||||
Bf::Src1 if is_alpha => Direct3D12::D3D12_BLEND_SRC1_ALPHA,
|
||||
Bf::Src1 => Direct3D12::D3D12_BLEND_SRC1_COLOR,
|
||||
Bf::OneMinusSrc1 if is_alpha => Direct3D12::D3D12_BLEND_INV_SRC1_ALPHA,
|
||||
Bf::OneMinusSrc1 => Direct3D12::D3D12_BLEND_INV_SRC1_COLOR,
|
||||
Bf::Src1Alpha => Direct3D12::D3D12_BLEND_SRC1_ALPHA,
|
||||
Bf::OneMinusSrc1Alpha => Direct3D12::D3D12_BLEND_INV_SRC1_ALPHA,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_blend_component(
|
||||
component: &wgt::BlendComponent,
|
||||
is_alpha: bool,
|
||||
) -> (
|
||||
Direct3D12::D3D12_BLEND_OP,
|
||||
Direct3D12::D3D12_BLEND,
|
||||
Direct3D12::D3D12_BLEND,
|
||||
) {
|
||||
let raw_op = match component.operation {
|
||||
wgt::BlendOperation::Add => Direct3D12::D3D12_BLEND_OP_ADD,
|
||||
wgt::BlendOperation::Subtract => Direct3D12::D3D12_BLEND_OP_SUBTRACT,
|
||||
wgt::BlendOperation::ReverseSubtract => Direct3D12::D3D12_BLEND_OP_REV_SUBTRACT,
|
||||
wgt::BlendOperation::Min => Direct3D12::D3D12_BLEND_OP_MIN,
|
||||
wgt::BlendOperation::Max => Direct3D12::D3D12_BLEND_OP_MAX,
|
||||
};
|
||||
let raw_src = map_blend_factor(component.src_factor, is_alpha);
|
||||
let raw_dst = map_blend_factor(component.dst_factor, is_alpha);
|
||||
(raw_op, raw_src, raw_dst)
|
||||
}
|
||||
|
||||
pub fn map_render_targets(
|
||||
color_targets: &[Option<wgt::ColorTargetState>],
|
||||
) -> [Direct3D12::D3D12_RENDER_TARGET_BLEND_DESC;
|
||||
Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize] {
|
||||
let dummy_target = Direct3D12::D3D12_RENDER_TARGET_BLEND_DESC {
|
||||
BlendEnable: false.into(),
|
||||
LogicOpEnable: false.into(),
|
||||
SrcBlend: Direct3D12::D3D12_BLEND_ZERO,
|
||||
DestBlend: Direct3D12::D3D12_BLEND_ZERO,
|
||||
BlendOp: Direct3D12::D3D12_BLEND_OP_ADD,
|
||||
SrcBlendAlpha: Direct3D12::D3D12_BLEND_ZERO,
|
||||
DestBlendAlpha: Direct3D12::D3D12_BLEND_ZERO,
|
||||
BlendOpAlpha: Direct3D12::D3D12_BLEND_OP_ADD,
|
||||
LogicOp: Direct3D12::D3D12_LOGIC_OP_CLEAR,
|
||||
RenderTargetWriteMask: 0,
|
||||
};
|
||||
let mut raw_targets =
|
||||
[dummy_target; Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize];
|
||||
|
||||
for (raw, ct) in raw_targets.iter_mut().zip(color_targets.iter()) {
|
||||
if let Some(ct) = ct.as_ref() {
|
||||
raw.RenderTargetWriteMask = ct.write_mask.bits() as u8;
|
||||
if let Some(ref blend) = ct.blend {
|
||||
let (color_op, color_src, color_dst) = map_blend_component(&blend.color, false);
|
||||
let (alpha_op, alpha_src, alpha_dst) = map_blend_component(&blend.alpha, true);
|
||||
raw.BlendEnable = true.into();
|
||||
raw.BlendOp = color_op;
|
||||
raw.SrcBlend = color_src;
|
||||
raw.DestBlend = color_dst;
|
||||
raw.BlendOpAlpha = alpha_op;
|
||||
raw.SrcBlendAlpha = alpha_src;
|
||||
raw.DestBlendAlpha = alpha_dst;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
raw_targets
|
||||
}
|
||||
|
||||
fn map_stencil_op(op: wgt::StencilOperation) -> Direct3D12::D3D12_STENCIL_OP {
|
||||
use wgt::StencilOperation as So;
|
||||
match op {
|
||||
So::Keep => Direct3D12::D3D12_STENCIL_OP_KEEP,
|
||||
So::Zero => Direct3D12::D3D12_STENCIL_OP_ZERO,
|
||||
So::Replace => Direct3D12::D3D12_STENCIL_OP_REPLACE,
|
||||
So::IncrementClamp => Direct3D12::D3D12_STENCIL_OP_INCR_SAT,
|
||||
So::IncrementWrap => Direct3D12::D3D12_STENCIL_OP_INCR,
|
||||
So::DecrementClamp => Direct3D12::D3D12_STENCIL_OP_DECR_SAT,
|
||||
So::DecrementWrap => Direct3D12::D3D12_STENCIL_OP_DECR,
|
||||
So::Invert => Direct3D12::D3D12_STENCIL_OP_INVERT,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_stencil_face(face: &wgt::StencilFaceState) -> Direct3D12::D3D12_DEPTH_STENCILOP_DESC {
|
||||
Direct3D12::D3D12_DEPTH_STENCILOP_DESC {
|
||||
StencilFailOp: map_stencil_op(face.fail_op),
|
||||
StencilDepthFailOp: map_stencil_op(face.depth_fail_op),
|
||||
StencilPassOp: map_stencil_op(face.pass_op),
|
||||
StencilFunc: map_comparison(face.compare),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_depth_stencil(ds: &wgt::DepthStencilState) -> Direct3D12::D3D12_DEPTH_STENCIL_DESC {
|
||||
Direct3D12::D3D12_DEPTH_STENCIL_DESC {
|
||||
DepthEnable: ds.is_depth_enabled().into(),
|
||||
DepthWriteMask: if ds.depth_write_enabled.unwrap_or_default() {
|
||||
Direct3D12::D3D12_DEPTH_WRITE_MASK_ALL
|
||||
} else {
|
||||
Direct3D12::D3D12_DEPTH_WRITE_MASK_ZERO
|
||||
},
|
||||
DepthFunc: map_comparison(ds.depth_compare.unwrap_or_default()),
|
||||
StencilEnable: ds.stencil.is_enabled().into(),
|
||||
StencilReadMask: ds.stencil.read_mask as u8,
|
||||
StencilWriteMask: ds.stencil.write_mask as u8,
|
||||
FrontFace: map_stencil_face(&ds.stencil.front),
|
||||
BackFace: map_stencil_face(&ds.stencil.back),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn map_acceleration_structure_build_flags(
|
||||
flags: wgt::AccelerationStructureFlags,
|
||||
mode: Option<crate::AccelerationStructureBuildMode>,
|
||||
) -> Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS {
|
||||
let mut d3d_flags = Default::default();
|
||||
if flags.contains(wgt::AccelerationStructureFlags::ALLOW_COMPACTION) {
|
||||
d3d_flags |=
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_COMPACTION;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::ALLOW_UPDATE) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::LOW_MEMORY) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::PREFER_FAST_BUILD) {
|
||||
d3d_flags |=
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_BUILD;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::PREFER_FAST_TRACE) {
|
||||
d3d_flags |=
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE;
|
||||
}
|
||||
|
||||
if let Some(crate::AccelerationStructureBuildMode::Update) = mode {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE
|
||||
}
|
||||
|
||||
d3d_flags
|
||||
}
|
||||
|
||||
pub(crate) fn map_acceleration_structure_geometry_flags(
|
||||
flags: wgt::AccelerationStructureGeometryFlags,
|
||||
) -> Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAGS {
|
||||
let mut d3d_flags = Default::default();
|
||||
if flags.contains(wgt::AccelerationStructureGeometryFlags::OPAQUE) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE;
|
||||
}
|
||||
if flags.contains(wgt::AccelerationStructureGeometryFlags::NO_DUPLICATE_ANY_HIT_INVOCATION) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAG_NO_DUPLICATE_ANYHIT_INVOCATION;
|
||||
}
|
||||
d3d_flags
|
||||
}
|
||||
|
||||
pub(crate) fn map_acceleration_structure_copy_mode(
|
||||
mode: wgt::AccelerationStructureCopy,
|
||||
) -> Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE {
|
||||
match mode {
|
||||
wgt::AccelerationStructureCopy::Clone => {
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE
|
||||
}
|
||||
wgt::AccelerationStructureCopy::Compact => {
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn make_shader_component_mapping(
|
||||
src0: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
src1: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
src2: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
src3: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
) -> Direct3D12::D3D12_SHADER_COMPONENT_MAPPING {
|
||||
const M: i32 = Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_MASK as i32;
|
||||
const S: i32 = Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_SHIFT as i32;
|
||||
Direct3D12::D3D12_SHADER_COMPONENT_MAPPING(
|
||||
(src0.0 & M)
|
||||
| (src1.0 & M) << S
|
||||
| (src2.0 & M) << (S * 2)
|
||||
| (src3.0 & M) << (S * 3)
|
||||
| Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES
|
||||
as i32,
|
||||
)
|
||||
}
|
||||
Vendored
+120
@@ -0,0 +1,120 @@
|
||||
use alloc::sync::Arc;
|
||||
use core::{ffi, ptr};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use windows::{
|
||||
core::Interface as _,
|
||||
Win32::{Foundation::HWND, Graphics::DirectComposition},
|
||||
};
|
||||
|
||||
use super::DynLib;
|
||||
|
||||
// Lazy-loaded DirectComposition library
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct DCompLib {
|
||||
lib: Lazy<Result<DynLib, crate::SurfaceError>>,
|
||||
}
|
||||
|
||||
impl DCompLib {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
lib: Lazy::new(|| unsafe {
|
||||
DynLib::new("dcomp.dll").map_err(|err| {
|
||||
log::error!("Error loading dcomp.dll: {err}");
|
||||
crate::SurfaceError::Other("Error loading dcomp.dll")
|
||||
})
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_lib(&self) -> Result<&DynLib, crate::SurfaceError> {
|
||||
match self.lib.as_ref() {
|
||||
Ok(lib) => Ok(lib),
|
||||
Err(err) => Err(err.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_device(
|
||||
&self,
|
||||
) -> Result<DirectComposition::IDCompositionDevice, crate::SurfaceError> {
|
||||
let lib = self.get_lib()?;
|
||||
|
||||
// Calls windows::Win32::Graphics::DirectComposition::DCompositionCreateDevice2 on dcomp.dll
|
||||
type Fun = extern "system" fn(
|
||||
pdxdevice: *mut ffi::c_void,
|
||||
riid: *const windows_core::GUID,
|
||||
ppdcompdevice: *mut *mut ffi::c_void,
|
||||
) -> windows_core::HRESULT;
|
||||
let func: libloading::Symbol<Fun> =
|
||||
unsafe { lib.get(c"DCompositionCreateDevice2".to_bytes()) }?;
|
||||
|
||||
let mut res: Option<DirectComposition::IDCompositionDevice> = None;
|
||||
|
||||
(func)(
|
||||
ptr::null_mut(),
|
||||
&DirectComposition::IDCompositionDevice::IID,
|
||||
<*mut _>::cast(&mut res),
|
||||
)
|
||||
.map(|| res.unwrap())
|
||||
.map_err(|err| {
|
||||
log::error!("DirectComposition::DCompositionCreateDevice2 failed: {err}");
|
||||
crate::SurfaceError::Other("DirectComposition::DCompositionCreateDevice2")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct DCompState {
|
||||
inner: Option<InnerState>,
|
||||
}
|
||||
|
||||
impl DCompState {
|
||||
/// This will create a DirectComposition device and a target for the window handle if not already initialized.
|
||||
/// If the device is already initialized, it will return the existing state.
|
||||
pub unsafe fn get_or_init(
|
||||
&mut self,
|
||||
lib: &Arc<DCompLib>,
|
||||
hwnd: &HWND,
|
||||
) -> Result<&mut InnerState, crate::SurfaceError> {
|
||||
if self.inner.is_none() {
|
||||
self.inner = Some(unsafe { InnerState::init(lib, hwnd) }?);
|
||||
}
|
||||
Ok(self.inner.as_mut().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InnerState {
|
||||
pub visual: DirectComposition::IDCompositionVisual,
|
||||
pub device: DirectComposition::IDCompositionDevice,
|
||||
// Must be kept alive but is otherwise unused after initialization.
|
||||
pub _target: DirectComposition::IDCompositionTarget,
|
||||
}
|
||||
|
||||
impl InnerState {
|
||||
/// Creates a DirectComposition device and a target for the given window handle.
|
||||
pub unsafe fn init(lib: &Arc<DCompLib>, hwnd: &HWND) -> Result<Self, crate::SurfaceError> {
|
||||
profiling::scope!("DCompState::init");
|
||||
let dcomp_device = lib.create_device()?;
|
||||
|
||||
let target = unsafe { dcomp_device.CreateTargetForHwnd(*hwnd, false) }.map_err(|err| {
|
||||
log::error!("IDCompositionDevice::CreateTargetForHwnd failed: {err}");
|
||||
crate::SurfaceError::Other("IDCompositionDevice::CreateTargetForHwnd")
|
||||
})?;
|
||||
|
||||
let visual = unsafe { dcomp_device.CreateVisual() }.map_err(|err| {
|
||||
log::error!("IDCompositionDevice::CreateVisual failed: {err}");
|
||||
crate::SurfaceError::Other("IDCompositionDevice::CreateVisual")
|
||||
})?;
|
||||
|
||||
unsafe { target.SetRoot(&visual) }.map_err(|err| {
|
||||
log::error!("IDCompositionTarget::SetRoot failed: {err}");
|
||||
crate::SurfaceError::Other("IDCompositionTarget::SetRoot")
|
||||
})?;
|
||||
|
||||
Ok(InnerState {
|
||||
visual,
|
||||
device: dcomp_device,
|
||||
_target: target,
|
||||
})
|
||||
}
|
||||
}
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
use alloc::vec::Vec;
|
||||
use core::fmt;
|
||||
|
||||
use bit_set::BitSet;
|
||||
use parking_lot::Mutex;
|
||||
use range_alloc::RangeAllocator;
|
||||
use windows::Win32::Graphics::Direct3D12;
|
||||
|
||||
use crate::auxil::dxgi::result::HResult as _;
|
||||
|
||||
const HEAP_SIZE_FIXED: usize = 64;
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub(super) struct DualHandle {
|
||||
cpu: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
pub gpu: Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE,
|
||||
/// How large the block allocated to this handle is.
|
||||
count: u64,
|
||||
}
|
||||
|
||||
impl fmt::Debug for DualHandle {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("DualHandle")
|
||||
.field("cpu", &self.cpu.ptr)
|
||||
.field("gpu", &self.gpu.ptr)
|
||||
.field("count", &self.count)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
type DescriptorIndex = u64;
|
||||
|
||||
pub(super) struct GeneralHeap {
|
||||
pub raw: Direct3D12::ID3D12DescriptorHeap,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
handle_size: u64,
|
||||
total_handles: u64,
|
||||
start: DualHandle,
|
||||
ranges: Mutex<RangeAllocator<DescriptorIndex>>,
|
||||
}
|
||||
|
||||
impl GeneralHeap {
|
||||
pub(super) fn new(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
total_handles: u64,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
let raw = {
|
||||
profiling::scope!("ID3D12Device::CreateDescriptorHeap");
|
||||
let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: ty,
|
||||
NumDescriptors: total_handles as u32,
|
||||
Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
|
||||
NodeMask: 0,
|
||||
};
|
||||
unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
|
||||
.into_device_result("Descriptor heap creation")?
|
||||
};
|
||||
|
||||
let start = DualHandle {
|
||||
cpu: unsafe { raw.GetCPUDescriptorHandleForHeapStart() },
|
||||
gpu: unsafe { raw.GetGPUDescriptorHandleForHeapStart() },
|
||||
count: 0,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
raw,
|
||||
ty,
|
||||
handle_size: unsafe { device.GetDescriptorHandleIncrementSize(ty) } as u64,
|
||||
total_handles,
|
||||
start,
|
||||
ranges: Mutex::new(RangeAllocator::new(0..total_handles)),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn at(&self, index: DescriptorIndex, count: u64) -> DualHandle {
|
||||
assert!(index < self.total_handles);
|
||||
DualHandle {
|
||||
cpu: self.cpu_descriptor_at(index),
|
||||
gpu: self.gpu_descriptor_at(index),
|
||||
count,
|
||||
}
|
||||
}
|
||||
|
||||
fn cpu_descriptor_at(&self, index: u64) -> Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.cpu.ptr + (self.handle_size * index) as usize,
|
||||
}
|
||||
}
|
||||
|
||||
fn gpu_descriptor_at(&self, index: u64) -> Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE {
|
||||
Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.gpu.ptr + self.handle_size * index,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn allocate_slice(&self, count: u64) -> Result<DescriptorIndex, crate::DeviceError> {
|
||||
let range = self.ranges.lock().allocate_range(count).map_err(|err| {
|
||||
log::error!("Unable to allocate descriptors: {err:?}");
|
||||
crate::DeviceError::OutOfMemory
|
||||
})?;
|
||||
Ok(range.start)
|
||||
}
|
||||
|
||||
/// Free handles previously given out by this `DescriptorHeapSlice`.
|
||||
/// Do not use this with handles not given out by this `DescriptorHeapSlice`.
|
||||
pub(crate) fn free_slice(&self, handle: DualHandle) {
|
||||
let start = (handle.gpu.ptr - self.start.gpu.ptr) / self.handle_size;
|
||||
self.ranges.lock().free_range(start..start + handle.count);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixed-size free-list allocator for CPU descriptors.
|
||||
struct FixedSizeHeap {
|
||||
_raw: Direct3D12::ID3D12DescriptorHeap,
|
||||
/// Bit flag representation of available handles in the heap.
|
||||
///
|
||||
/// 0 - Occupied
|
||||
/// 1 - free
|
||||
availability: u64,
|
||||
handle_size: usize,
|
||||
start: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
}
|
||||
|
||||
impl FixedSizeHeap {
|
||||
fn new(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: ty,
|
||||
NumDescriptors: HEAP_SIZE_FIXED as u32,
|
||||
Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
|
||||
NodeMask: 0,
|
||||
};
|
||||
let heap =
|
||||
unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
|
||||
.into_device_result("Descriptor heap creation")?;
|
||||
|
||||
Ok(Self {
|
||||
handle_size: unsafe { device.GetDescriptorHandleIncrementSize(ty) } as usize,
|
||||
availability: !0, // all free!
|
||||
start: unsafe { heap.GetCPUDescriptorHandleForHeapStart() },
|
||||
_raw: heap,
|
||||
})
|
||||
}
|
||||
|
||||
fn alloc_handle(
|
||||
&mut self,
|
||||
) -> Result<Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE, crate::DeviceError> {
|
||||
// Find first free slot.
|
||||
let slot = self.availability.trailing_zeros() as usize;
|
||||
if slot >= HEAP_SIZE_FIXED {
|
||||
log::error!("Failed to allocate a handle form a fixed size heap");
|
||||
return Err(crate::DeviceError::OutOfMemory);
|
||||
}
|
||||
// Set the slot as occupied.
|
||||
self.availability ^= 1 << slot;
|
||||
|
||||
Ok(Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.ptr + self.handle_size * slot,
|
||||
})
|
||||
}
|
||||
|
||||
fn free_handle(&mut self, handle: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
let slot = (handle.ptr - self.start.ptr) / self.handle_size;
|
||||
assert!(slot < HEAP_SIZE_FIXED);
|
||||
assert_eq!(self.availability & (1 << slot), 0);
|
||||
self.availability ^= 1 << slot;
|
||||
}
|
||||
|
||||
fn is_full(&self) -> bool {
|
||||
self.availability == 0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Handle {
|
||||
pub raw: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
heap_index: usize,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Handle {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
fmt.debug_struct("Handle")
|
||||
.field("ptr", &self.raw.ptr)
|
||||
.field("heap_index", &self.heap_index)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct CpuPool {
|
||||
device: Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
heaps: Vec<FixedSizeHeap>,
|
||||
available_heap_indices: BitSet,
|
||||
}
|
||||
|
||||
impl CpuPool {
|
||||
pub(super) fn new(
|
||||
device: Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
) -> Self {
|
||||
Self {
|
||||
device,
|
||||
ty,
|
||||
heaps: Vec::new(),
|
||||
available_heap_indices: BitSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn alloc_handle(&mut self) -> Result<Handle, crate::DeviceError> {
|
||||
let heap_index = self
|
||||
.available_heap_indices
|
||||
.iter()
|
||||
.next()
|
||||
.unwrap_or(self.heaps.len());
|
||||
|
||||
// Allocate a new heap
|
||||
if heap_index == self.heaps.len() {
|
||||
self.heaps.push(FixedSizeHeap::new(&self.device, self.ty)?);
|
||||
self.available_heap_indices.insert(heap_index);
|
||||
}
|
||||
|
||||
let heap = &mut self.heaps[heap_index];
|
||||
let handle = Handle {
|
||||
raw: heap.alloc_handle()?,
|
||||
heap_index,
|
||||
};
|
||||
if heap.is_full() {
|
||||
self.available_heap_indices.remove(heap_index);
|
||||
}
|
||||
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
pub(super) fn free_handle(&mut self, handle: Handle) {
|
||||
self.heaps[handle.heap_index].free_handle(handle.raw);
|
||||
self.available_heap_indices.insert(handle.heap_index);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct CpuHeapInner {
|
||||
pub _raw: Direct3D12::ID3D12DescriptorHeap,
|
||||
pub stage: Vec<Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE>,
|
||||
}
|
||||
|
||||
pub(super) struct CpuHeap {
|
||||
pub inner: Mutex<CpuHeapInner>,
|
||||
start: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
handle_size: u32,
|
||||
total: u32,
|
||||
}
|
||||
|
||||
unsafe impl Send for CpuHeap {}
|
||||
unsafe impl Sync for CpuHeap {}
|
||||
|
||||
impl CpuHeap {
|
||||
pub(super) fn new(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
total: u32,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
let handle_size = unsafe { device.GetDescriptorHandleIncrementSize(ty) };
|
||||
let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: ty,
|
||||
NumDescriptors: total,
|
||||
Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
|
||||
NodeMask: 0,
|
||||
};
|
||||
let raw = unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
|
||||
.into_device_result("CPU descriptor heap creation")?;
|
||||
|
||||
let start = unsafe { raw.GetCPUDescriptorHandleForHeapStart() };
|
||||
|
||||
Ok(Self {
|
||||
inner: Mutex::new(CpuHeapInner {
|
||||
_raw: raw,
|
||||
stage: Vec::new(),
|
||||
}),
|
||||
start,
|
||||
handle_size,
|
||||
total,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn at(&self, index: u32) -> Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
debug_assert!(
|
||||
index < self.total,
|
||||
"Index ({index}) out of bounds {total}",
|
||||
total = self.total
|
||||
);
|
||||
Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.ptr + (self.handle_size * index) as usize,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for CpuHeap {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("CpuHeap")
|
||||
.field("start", &self.start.ptr)
|
||||
.field("handle_size", &self.handle_size)
|
||||
.field("total", &self.total)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) unsafe fn upload(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
src: &CpuHeapInner,
|
||||
dst: &GeneralHeap,
|
||||
dummy_copy_counts: &[u32],
|
||||
) -> Result<DualHandle, crate::DeviceError> {
|
||||
let count = src.stage.len() as u32;
|
||||
let index = dst.allocate_slice(count as u64)?;
|
||||
unsafe {
|
||||
device.CopyDescriptors(
|
||||
1,
|
||||
&dst.cpu_descriptor_at(index),
|
||||
Some(&count),
|
||||
count,
|
||||
src.stage.as_ptr(),
|
||||
Some(dummy_copy_counts.as_ptr()),
|
||||
dst.ty,
|
||||
)
|
||||
};
|
||||
Ok(dst.at(index, count as u64))
|
||||
}
|
||||
Vendored
+2691
File diff suppressed because it is too large
Load Diff
+176
@@ -0,0 +1,176 @@
|
||||
use alloc::sync::Arc;
|
||||
use core::ops::Deref;
|
||||
|
||||
use windows::core::Interface as _;
|
||||
use windows::Win32::Graphics::{Direct3D, Direct3D12};
|
||||
|
||||
use super::D3D12Lib;
|
||||
use crate::auxil::dxgi::factory::DxgiAdapter;
|
||||
|
||||
/// Abstraction over D3D12 device creation.
|
||||
///
|
||||
/// Supports two paths:
|
||||
/// - **Independent**: Uses `ID3D12DeviceFactory` from the Agility SDK's Independent Devices API.
|
||||
/// - **Legacy**: Uses the traditional `D3D12CreateDevice` export.
|
||||
pub(super) enum DeviceFactory {
|
||||
/// Uses `ID3D12DeviceFactory` from the Independent Devices API.
|
||||
Independent(Direct3D12::ID3D12DeviceFactory),
|
||||
/// Uses the traditional `D3D12CreateDevice` export.
|
||||
Legacy,
|
||||
}
|
||||
|
||||
impl DeviceFactory {
|
||||
/// Create a new `DeviceFactory`.
|
||||
///
|
||||
/// If `agility_sdk` is `Some`, attempts to set up the Independent Devices API path.
|
||||
/// On failure, the behavior depends on
|
||||
/// [`on_load_failure`](wgt::Dx12AgilitySDKLoadFailure):
|
||||
/// - [`Fallback`](wgt::Dx12AgilitySDKLoadFailure::Fallback): logs a warning and
|
||||
/// returns `Ok(Legacy)`.
|
||||
/// - [`Error`](wgt::Dx12AgilitySDKLoadFailure::Error): returns an `Err`.
|
||||
pub(super) fn new(
|
||||
lib: &D3D12Lib,
|
||||
agility_sdk: Option<&wgt::Dx12AgilitySDK>,
|
||||
) -> Result<Self, crate::InstanceError> {
|
||||
let Some(agility_sdk) = agility_sdk else {
|
||||
log::debug!("No D3D12 Agility SDK configuration provided; using system D3D12 runtime");
|
||||
return Ok(Self::Legacy);
|
||||
};
|
||||
|
||||
match Self::try_create_independent(lib, agility_sdk) {
|
||||
Ok(factory) => {
|
||||
log::debug!(
|
||||
"Using D3D12 Agility SDK v{} from '{}'",
|
||||
agility_sdk.sdk_version,
|
||||
agility_sdk.sdk_path
|
||||
);
|
||||
Ok(Self::Independent(factory))
|
||||
}
|
||||
Err(err) => {
|
||||
let message = format!(
|
||||
"Failed to initialize D3D12 Agility SDK (v{} at '{}'): {err}",
|
||||
agility_sdk.sdk_version, agility_sdk.sdk_path
|
||||
);
|
||||
|
||||
match agility_sdk.on_load_failure {
|
||||
wgt::Dx12AgilitySDKLoadFailure::Fallback => {
|
||||
log::warn!("{message}; falling back to system D3D12 runtime");
|
||||
Ok(Self::Legacy)
|
||||
}
|
||||
wgt::Dx12AgilitySDKLoadFailure::Error => {
|
||||
Err(crate::InstanceError::new(message))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn try_create_independent(
|
||||
lib: &D3D12Lib,
|
||||
agility_sdk: &wgt::Dx12AgilitySDK,
|
||||
) -> Result<Direct3D12::ID3D12DeviceFactory, DeviceFactoryError> {
|
||||
// Step 1: Get ID3D12SDKConfiguration1 via D3D12GetInterface
|
||||
let sdk_config: Direct3D12::ID3D12SDKConfiguration1 = lib
|
||||
.get_interface(&Direct3D12::CLSID_D3D12SDKConfiguration)
|
||||
.map_err(DeviceFactoryError::GetInterface)?;
|
||||
|
||||
// Step 2: Create device factory with the specified SDK version and path
|
||||
let sdk_path = std::ffi::CString::new(agility_sdk.sdk_path.as_bytes())
|
||||
.map_err(|_| DeviceFactoryError::InvalidPath)?;
|
||||
let factory: Direct3D12::ID3D12DeviceFactory = unsafe {
|
||||
sdk_config.CreateDeviceFactory(
|
||||
agility_sdk.sdk_version,
|
||||
windows::core::PCSTR(sdk_path.as_ptr().cast::<u8>()),
|
||||
)
|
||||
}
|
||||
.map_err(DeviceFactoryError::CreateDeviceFactory)?;
|
||||
|
||||
Ok(factory)
|
||||
}
|
||||
|
||||
/// Enable the D3D12 debug layer and optionally GPU-based validation.
|
||||
///
|
||||
/// - **Legacy**: configures debug globally via `D3D12GetDebugInterface`.
|
||||
/// - **Independent**: uses `GetConfigurationInterface` to get an
|
||||
/// `ID3D12Debug` scoped to the factory.
|
||||
pub(super) fn enable_debug_layer(&self, lib: &D3D12Lib, flags: wgt::InstanceFlags) {
|
||||
if !flags
|
||||
.intersects(wgt::InstanceFlags::VALIDATION | wgt::InstanceFlags::GPU_BASED_VALIDATION)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let debug_controller = match self {
|
||||
Self::Independent(factory) => {
|
||||
match unsafe {
|
||||
factory.GetConfigurationInterface::<Direct3D12::ID3D12Debug>(
|
||||
&Direct3D12::CLSID_D3D12Debug,
|
||||
)
|
||||
} {
|
||||
Ok(debug) => debug,
|
||||
Err(err) => {
|
||||
log::warn!("Failed to get debug interface from device factory: {err}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::Legacy => match lib.debug_interface() {
|
||||
Ok(Some(debug)) => debug,
|
||||
Ok(None) => return,
|
||||
Err(err) => {
|
||||
log::warn!("Failed to get debug interface: {err}");
|
||||
return;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
if flags.intersects(wgt::InstanceFlags::VALIDATION) {
|
||||
unsafe { debug_controller.EnableDebugLayer() }
|
||||
}
|
||||
if flags.intersects(wgt::InstanceFlags::GPU_BASED_VALIDATION) {
|
||||
if let Ok(debug1) = debug_controller.cast::<Direct3D12::ID3D12Debug1>() {
|
||||
unsafe { debug1.SetEnableGPUBasedValidation(true) }
|
||||
} else {
|
||||
log::warn!("Failed to enable GPU-based validation");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a D3D12 device using the appropriate method.
|
||||
pub(super) fn create_device(
|
||||
&self,
|
||||
lib: &Arc<D3D12Lib>,
|
||||
adapter: &DxgiAdapter,
|
||||
feature_level: Direct3D::D3D_FEATURE_LEVEL,
|
||||
) -> Result<Direct3D12::ID3D12Device, super::CreateDeviceError> {
|
||||
match self {
|
||||
Self::Independent(factory) => {
|
||||
let mut result__: Option<Direct3D12::ID3D12Device> = None;
|
||||
unsafe { factory.CreateDevice(adapter.deref(), feature_level, &mut result__) }
|
||||
.map_err(|e| super::CreateDeviceError::D3D12CreateDevice(e.into()))?;
|
||||
|
||||
result__.ok_or(super::CreateDeviceError::RetDeviceIsNull)
|
||||
}
|
||||
Self::Legacy => lib.create_device(adapter, feature_level),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for DeviceFactory {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::Independent(_) => write!(f, "DeviceFactory::Independent"),
|
||||
Self::Legacy => write!(f, "DeviceFactory::Legacy"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum DeviceFactoryError {
|
||||
#[error("failed to get ID3D12SDKConfiguration1: {0}")]
|
||||
GetInterface(super::GetInterfaceError),
|
||||
#[error("SDK path contains null bytes")]
|
||||
InvalidPath,
|
||||
#[error("CreateDeviceFactory failed: {0}")]
|
||||
CreateDeviceFactory(windows::core::Error),
|
||||
}
|
||||
Vendored
+189
@@ -0,0 +1,189 @@
|
||||
use alloc::{string::String, sync::Arc, vec::Vec};
|
||||
|
||||
use parking_lot::RwLock;
|
||||
use windows::Win32::{Foundation, Graphics::Dxgi};
|
||||
|
||||
use super::SurfaceTarget;
|
||||
use crate::{
|
||||
auxil,
|
||||
dx12::{
|
||||
device_creation::DeviceFactory, shader_compilation::CompilerContainer, D3D12Lib, DCompLib,
|
||||
},
|
||||
};
|
||||
|
||||
impl crate::Instance for super::Instance {
|
||||
type A = super::Api;
|
||||
|
||||
unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> {
|
||||
profiling::scope!("Init DX12 Backend");
|
||||
let lib_main = D3D12Lib::new().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("failed to load d3d12.dll"), e)
|
||||
})?;
|
||||
|
||||
// Create DeviceFactory first so we know which debug path to use
|
||||
let device_factory =
|
||||
DeviceFactory::new(&lib_main, desc.backend_options.dx12.agility_sdk.as_ref())?;
|
||||
|
||||
device_factory.enable_debug_layer(&lib_main, desc.flags);
|
||||
|
||||
let (lib_dxgi, factory) = auxil::dxgi::factory::create_factory(desc.flags)?;
|
||||
|
||||
// Create IDXGIFactoryMedia
|
||||
let factory_media = lib_dxgi.create_factory_media().ok();
|
||||
|
||||
let mut supports_allow_tearing = false;
|
||||
if let Some(factory5) = factory.as_factory5() {
|
||||
let mut allow_tearing = Foundation::FALSE;
|
||||
let hr = unsafe {
|
||||
factory5.CheckFeatureSupport(
|
||||
Dxgi::DXGI_FEATURE_PRESENT_ALLOW_TEARING,
|
||||
<*mut _>::cast(&mut allow_tearing),
|
||||
size_of_val(&allow_tearing) as u32,
|
||||
)
|
||||
};
|
||||
|
||||
match hr {
|
||||
Err(err) => log::warn!("Unable to check for tearing support: {err}"),
|
||||
Ok(()) => supports_allow_tearing = true,
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize the shader compiler
|
||||
let compiler_container = match desc.backend_options.dx12.shader_compiler.clone() {
|
||||
wgt::Dx12Compiler::DynamicDxc { dxc_path } => {
|
||||
CompilerContainer::new_dynamic_dxc(dxc_path.into()).map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("Failed to load dynamic DXC"), e)
|
||||
})?
|
||||
}
|
||||
wgt::Dx12Compiler::StaticDxc => CompilerContainer::new_static_dxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("Failed to load static DXC"), e)
|
||||
})?,
|
||||
wgt::Dx12Compiler::Fxc => CompilerContainer::new_fxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("Failed to load FXC"), e)
|
||||
})?,
|
||||
wgt::Dx12Compiler::Auto => {
|
||||
if cfg!(static_dxc) {
|
||||
// Prefer static DXC if its compiled in
|
||||
CompilerContainer::new_static_dxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(
|
||||
String::from("Failed to load static DXC"),
|
||||
e,
|
||||
)
|
||||
})?
|
||||
} else {
|
||||
// Try to load dynamic DXC
|
||||
let dynamic = CompilerContainer::new_dynamic_dxc("dxcompiler.dll".into());
|
||||
match dynamic {
|
||||
Ok(v) => v,
|
||||
Err(super::shader_compilation::GetContainerError::FailedToLoad(..)) => {
|
||||
// If it can't be found load FXC
|
||||
CompilerContainer::new_fxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(
|
||||
String::from("Failed to load FXC"),
|
||||
e,
|
||||
)
|
||||
})?
|
||||
}
|
||||
Err(e) => {
|
||||
// If another error occurs when loading static DXC return that error
|
||||
return Err(crate::InstanceError::with_source(
|
||||
String::from("Failed to load dynamic DXC"),
|
||||
e,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
match compiler_container {
|
||||
CompilerContainer::DynamicDxc(..) => {
|
||||
log::debug!("Using dynamic DXC for shader compilation")
|
||||
}
|
||||
CompilerContainer::StaticDxc(..) => {
|
||||
log::debug!("Using static DXC for shader compilation")
|
||||
}
|
||||
CompilerContainer::Fxc(..) => {
|
||||
log::debug!("Using FXC for shader compilation")
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
// The call to create_factory will only succeed if we get a factory4, so this is safe.
|
||||
factory,
|
||||
factory_media,
|
||||
library: Arc::new(lib_main),
|
||||
device_factory: Arc::new(device_factory),
|
||||
dcomp_lib: Arc::new(DCompLib::new()),
|
||||
presentation_system: desc.backend_options.dx12.presentation_system,
|
||||
_lib_dxgi: lib_dxgi,
|
||||
supports_allow_tearing,
|
||||
flags: desc.flags,
|
||||
memory_budget_thresholds: desc.memory_budget_thresholds,
|
||||
compiler_container: Arc::new(compiler_container),
|
||||
options: desc.backend_options.dx12.clone(),
|
||||
telemetry: desc.telemetry,
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn create_surface(
|
||||
&self,
|
||||
display_handle: raw_window_handle::RawDisplayHandle,
|
||||
window_handle: raw_window_handle::RawWindowHandle,
|
||||
) -> Result<super::Surface, crate::InstanceError> {
|
||||
assert!(matches!(
|
||||
display_handle,
|
||||
raw_window_handle::RawDisplayHandle::Windows(_)
|
||||
));
|
||||
match window_handle {
|
||||
raw_window_handle::RawWindowHandle::Win32(handle) => {
|
||||
// https://github.com/rust-windowing/raw-window-handle/issues/171
|
||||
let handle = Foundation::HWND(handle.hwnd.get() as *mut _);
|
||||
let target = match self.presentation_system {
|
||||
wgt::Dx12SwapchainKind::DxgiFromHwnd => SurfaceTarget::WndHandle(handle),
|
||||
wgt::Dx12SwapchainKind::DxgiFromVisual => SurfaceTarget::VisualFromWndHandle {
|
||||
handle,
|
||||
dcomp_state: Default::default(),
|
||||
},
|
||||
};
|
||||
|
||||
Ok(super::Surface {
|
||||
factory: self.factory.clone(),
|
||||
factory_media: self.factory_media.clone(),
|
||||
target,
|
||||
supports_allow_tearing: self.supports_allow_tearing,
|
||||
swap_chain: RwLock::new(None),
|
||||
options: self.options.clone(),
|
||||
hdr_source: Some(auxil::dxgi::hdr::DxgiHdrSource::new(handle)),
|
||||
})
|
||||
}
|
||||
_ => Err(crate::InstanceError::new(format!(
|
||||
"window handle {window_handle:?} is not a Win32 handle"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn enumerate_adapters(
|
||||
&self,
|
||||
_surface_hint: Option<&super::Surface>,
|
||||
) -> Vec<crate::ExposedAdapter<super::Api>> {
|
||||
let adapters = auxil::dxgi::factory::enumerate_adapters(self.factory.clone());
|
||||
|
||||
adapters
|
||||
.into_iter()
|
||||
.filter_map(|raw| {
|
||||
super::Adapter::expose(
|
||||
raw,
|
||||
&self.library,
|
||||
&self.device_factory,
|
||||
&self.dcomp_lib,
|
||||
self.flags,
|
||||
self.memory_budget_thresholds,
|
||||
self.compiler_container.clone(),
|
||||
self.options.clone(),
|
||||
self.telemetry,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user