style: cargo fmt with the workspace tab policy (hard_tabs)

Whitespace only; the fork has no own rustfmt.toml so the Oak root
policy applies.
This commit is contained in:
2026-08-11 23:06:13 +08:00
parent 507d7e6e8d
commit af5482d774
318 changed files with 132564 additions and 132170 deletions
File diff suppressed because it is too large Load Diff
+386 -386
View File
@@ -2,8 +2,8 @@ use anyhow::{Context as _, Result};
use collections::FxHashMap;
use etagere::{BucketedAtlasAllocator, size2};
use gpui::{
AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTextureList, AtlasTile, Bounds, DevicePixels,
PlatformAtlas, Point, Size,
AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTextureList, AtlasTile, Bounds, DevicePixels,
PlatformAtlas, Point, Size,
};
use parking_lot::Mutex;
use std::{borrow::Cow, ops, sync::Arc};
@@ -11,471 +11,471 @@ use std::{borrow::Cow, ops, sync::Arc};
use crate::WgpuContext;
fn device_size_to_etagere(size: Size<DevicePixels>) -> etagere::Size {
size2(size.width.0, size.height.0)
size2(size.width.0, size.height.0)
}
fn etagere_point_to_device(point: etagere::Point) -> Point<DevicePixels> {
Point {
x: DevicePixels(point.x),
y: DevicePixels(point.y),
}
Point {
x: DevicePixels(point.x),
y: DevicePixels(point.y),
}
}
pub struct WgpuAtlas(Mutex<WgpuAtlasState>);
struct PendingUpload {
id: AtlasTextureId,
bounds: Bounds<DevicePixels>,
data: Vec<u8>,
id: AtlasTextureId,
bounds: Bounds<DevicePixels>,
data: Vec<u8>,
}
struct WgpuAtlasState {
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
max_texture_size: u32,
color_texture_format: wgpu::TextureFormat,
storage: WgpuAtlasStorage,
tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
pending_uploads: Vec<PendingUpload>,
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
max_texture_size: u32,
color_texture_format: wgpu::TextureFormat,
storage: WgpuAtlasStorage,
tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
pending_uploads: Vec<PendingUpload>,
}
pub struct WgpuTextureInfo {
pub view: wgpu::TextureView,
pub view: wgpu::TextureView,
}
impl WgpuAtlas {
pub fn new(
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
color_texture_format: wgpu::TextureFormat,
) -> Self {
let max_texture_size = device.limits().max_texture_dimension_2d;
WgpuAtlas(Mutex::new(WgpuAtlasState {
device,
queue,
max_texture_size,
color_texture_format,
storage: WgpuAtlasStorage::default(),
tiles_by_key: Default::default(),
pending_uploads: Vec::new(),
}))
}
pub fn new(
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
color_texture_format: wgpu::TextureFormat,
) -> Self {
let max_texture_size = device.limits().max_texture_dimension_2d;
WgpuAtlas(Mutex::new(WgpuAtlasState {
device,
queue,
max_texture_size,
color_texture_format,
storage: WgpuAtlasStorage::default(),
tiles_by_key: Default::default(),
pending_uploads: Vec::new(),
}))
}
pub fn from_context(context: &WgpuContext) -> Self {
Self::new(
context.device.clone(),
context.queue.clone(),
context.color_texture_format(),
)
}
pub fn from_context(context: &WgpuContext) -> Self {
Self::new(
context.device.clone(),
context.queue.clone(),
context.color_texture_format(),
)
}
pub fn before_frame(&self) {
let mut lock = self.0.lock();
lock.flush_uploads();
}
pub fn before_frame(&self) {
let mut lock = self.0.lock();
lock.flush_uploads();
}
pub fn get_texture_info(&self, id: AtlasTextureId) -> WgpuTextureInfo {
let lock = self.0.lock();
let texture = &lock.storage[id];
WgpuTextureInfo {
view: texture.view.clone(),
}
}
pub fn get_texture_info(&self, id: AtlasTextureId) -> WgpuTextureInfo {
let lock = self.0.lock();
let texture = &lock.storage[id];
WgpuTextureInfo {
view: texture.view.clone(),
}
}
/// Clears all cached textures and tiles, forcing them to be recreated.
/// Use this for incremental recovery when the device is still valid.
pub fn clear(&self) {
let mut lock = self.0.lock();
lock.storage = WgpuAtlasStorage::default();
lock.tiles_by_key.clear();
lock.pending_uploads.clear();
}
/// Clears all cached textures and tiles, forcing them to be recreated.
/// Use this for incremental recovery when the device is still valid.
pub fn clear(&self) {
let mut lock = self.0.lock();
lock.storage = WgpuAtlasStorage::default();
lock.tiles_by_key.clear();
lock.pending_uploads.clear();
}
/// Handles device lost by clearing all textures and cached tiles.
/// The atlas will lazily recreate textures as needed on subsequent frames.
pub fn handle_device_lost(&self, context: &WgpuContext) {
let mut lock = self.0.lock();
lock.device = context.device.clone();
lock.queue = context.queue.clone();
lock.color_texture_format = context.color_texture_format();
lock.storage = WgpuAtlasStorage::default();
lock.tiles_by_key.clear();
lock.pending_uploads.clear();
}
/// Handles device lost by clearing all textures and cached tiles.
/// The atlas will lazily recreate textures as needed on subsequent frames.
pub fn handle_device_lost(&self, context: &WgpuContext) {
let mut lock = self.0.lock();
lock.device = context.device.clone();
lock.queue = context.queue.clone();
lock.color_texture_format = context.color_texture_format();
lock.storage = WgpuAtlasStorage::default();
lock.tiles_by_key.clear();
lock.pending_uploads.clear();
}
}
impl PlatformAtlas for WgpuAtlas {
fn get_or_insert_with<'a>(
&self,
key: &AtlasKey,
build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
) -> Result<Option<AtlasTile>> {
let mut lock = self.0.lock();
if let Some(tile) = lock.tiles_by_key.get(key) {
Ok(Some(*tile))
} else {
profiling::scope!("new tile");
let Some((size, bytes)) = build()? else {
return Ok(None);
};
let tile = lock
.allocate(size, key.texture_kind())
.context("failed to allocate")?;
lock.upload_texture(tile.texture_id, tile.bounds, &bytes);
lock.tiles_by_key.insert(key.clone(), tile);
Ok(Some(tile))
}
}
fn get_or_insert_with<'a>(
&self,
key: &AtlasKey,
build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
) -> Result<Option<AtlasTile>> {
let mut lock = self.0.lock();
if let Some(tile) = lock.tiles_by_key.get(key) {
Ok(Some(*tile))
} else {
profiling::scope!("new tile");
let Some((size, bytes)) = build()? else {
return Ok(None);
};
let tile = lock
.allocate(size, key.texture_kind())
.context("failed to allocate")?;
lock.upload_texture(tile.texture_id, tile.bounds, &bytes);
lock.tiles_by_key.insert(key.clone(), tile);
Ok(Some(tile))
}
}
fn remove(&self, key: &AtlasKey) {
let mut lock = self.0.lock();
fn remove(&self, key: &AtlasKey) {
let mut lock = self.0.lock();
let Some(id) = lock.tiles_by_key.remove(key).map(|tile| tile.texture_id) else {
return;
};
let Some(id) = lock.tiles_by_key.remove(key).map(|tile| tile.texture_id) else {
return;
};
let Some(texture_slot) = lock.storage[id.kind].textures.get_mut(id.index as usize) else {
return;
};
let Some(texture_slot) = lock.storage[id.kind].textures.get_mut(id.index as usize) else {
return;
};
if let Some(mut texture) = texture_slot.take() {
texture.decrement_ref_count();
if texture.is_unreferenced() {
lock.pending_uploads
.retain(|upload| upload.id != texture.id);
lock.storage[id.kind]
.free_list
.push(texture.id.index as usize);
} else {
*texture_slot = Some(texture);
}
}
}
if let Some(mut texture) = texture_slot.take() {
texture.decrement_ref_count();
if texture.is_unreferenced() {
lock.pending_uploads
.retain(|upload| upload.id != texture.id);
lock.storage[id.kind]
.free_list
.push(texture.id.index as usize);
} else {
*texture_slot = Some(texture);
}
}
}
}
impl WgpuAtlasState {
fn allocate(
&mut self,
size: Size<DevicePixels>,
texture_kind: AtlasTextureKind,
) -> Option<AtlasTile> {
{
let textures = &mut self.storage[texture_kind];
fn allocate(
&mut self,
size: Size<DevicePixels>,
texture_kind: AtlasTextureKind,
) -> Option<AtlasTile> {
{
let textures = &mut self.storage[texture_kind];
if let Some(tile) = textures
.iter_mut()
.rev()
.find_map(|texture| texture.allocate(size))
{
return Some(tile);
}
}
if let Some(tile) = textures
.iter_mut()
.rev()
.find_map(|texture| texture.allocate(size))
{
return Some(tile);
}
}
let texture = self.push_texture(size, texture_kind);
texture.allocate(size)
}
let texture = self.push_texture(size, texture_kind);
texture.allocate(size)
}
fn push_texture(
&mut self,
min_size: Size<DevicePixels>,
kind: AtlasTextureKind,
) -> &mut WgpuAtlasTexture {
const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
width: DevicePixels(1024),
height: DevicePixels(1024),
};
let max_texture_size = self.max_texture_size as i32;
let max_atlas_size = Size {
width: DevicePixels(max_texture_size),
height: DevicePixels(max_texture_size),
};
fn push_texture(
&mut self,
min_size: Size<DevicePixels>,
kind: AtlasTextureKind,
) -> &mut WgpuAtlasTexture {
const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
width: DevicePixels(1024),
height: DevicePixels(1024),
};
let max_texture_size = self.max_texture_size as i32;
let max_atlas_size = Size {
width: DevicePixels(max_texture_size),
height: DevicePixels(max_texture_size),
};
let size = min_size.min(&max_atlas_size).max(&DEFAULT_ATLAS_SIZE);
let format = match kind {
AtlasTextureKind::Monochrome => wgpu::TextureFormat::R8Unorm,
AtlasTextureKind::Subpixel | AtlasTextureKind::Polychrome => self.color_texture_format,
};
let size = min_size.min(&max_atlas_size).max(&DEFAULT_ATLAS_SIZE);
let format = match kind {
AtlasTextureKind::Monochrome => wgpu::TextureFormat::R8Unorm,
AtlasTextureKind::Subpixel | AtlasTextureKind::Polychrome => self.color_texture_format,
};
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("atlas"),
size: wgpu::Extent3d {
width: size.width.0 as u32,
height: size.height.0 as u32,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("atlas"),
size: wgpu::Extent3d {
width: size.width.0 as u32,
height: size.height.0 as u32,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let texture_list = &mut self.storage[kind];
let index = texture_list.free_list.pop();
let texture_list = &mut self.storage[kind];
let index = texture_list.free_list.pop();
let atlas_texture = WgpuAtlasTexture {
id: AtlasTextureId {
index: index.unwrap_or(texture_list.textures.len()) as u32,
kind,
},
allocator: BucketedAtlasAllocator::new(device_size_to_etagere(size)),
format,
texture,
view,
live_atlas_keys: 0,
};
let atlas_texture = WgpuAtlasTexture {
id: AtlasTextureId {
index: index.unwrap_or(texture_list.textures.len()) as u32,
kind,
},
allocator: BucketedAtlasAllocator::new(device_size_to_etagere(size)),
format,
texture,
view,
live_atlas_keys: 0,
};
if let Some(ix) = index {
texture_list.textures[ix] = Some(atlas_texture);
texture_list
.textures
.get_mut(ix)
.and_then(|t| t.as_mut())
.expect("texture must exist")
} else {
texture_list.textures.push(Some(atlas_texture));
texture_list
.textures
.last_mut()
.and_then(|t| t.as_mut())
.expect("texture must exist")
}
}
if let Some(ix) = index {
texture_list.textures[ix] = Some(atlas_texture);
texture_list
.textures
.get_mut(ix)
.and_then(|t| t.as_mut())
.expect("texture must exist")
} else {
texture_list.textures.push(Some(atlas_texture));
texture_list
.textures
.last_mut()
.and_then(|t| t.as_mut())
.expect("texture must exist")
}
}
fn upload_texture(&mut self, id: AtlasTextureId, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
let data = self
.storage
.get(id)
.map(|texture| swizzle_upload_data(bytes, texture.format))
.unwrap_or_else(|| bytes.to_vec());
fn upload_texture(&mut self, id: AtlasTextureId, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
let data = self
.storage
.get(id)
.map(|texture| swizzle_upload_data(bytes, texture.format))
.unwrap_or_else(|| bytes.to_vec());
self.pending_uploads
.push(PendingUpload { id, bounds, data });
}
self.pending_uploads
.push(PendingUpload { id, bounds, data });
}
fn flush_uploads(&mut self) {
for upload in self.pending_uploads.drain(..) {
let Some(texture) = self.storage.get(upload.id) else {
continue;
};
let bytes_per_pixel = texture.bytes_per_pixel();
fn flush_uploads(&mut self) {
for upload in self.pending_uploads.drain(..) {
let Some(texture) = self.storage.get(upload.id) else {
continue;
};
let bytes_per_pixel = texture.bytes_per_pixel();
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture.texture,
mip_level: 0,
origin: wgpu::Origin3d {
x: upload.bounds.origin.x.0 as u32,
y: upload.bounds.origin.y.0 as u32,
z: 0,
},
aspect: wgpu::TextureAspect::All,
},
&upload.data,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(upload.bounds.size.width.0 as u32 * bytes_per_pixel as u32),
rows_per_image: None,
},
wgpu::Extent3d {
width: upload.bounds.size.width.0 as u32,
height: upload.bounds.size.height.0 as u32,
depth_or_array_layers: 1,
},
);
}
}
self.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture.texture,
mip_level: 0,
origin: wgpu::Origin3d {
x: upload.bounds.origin.x.0 as u32,
y: upload.bounds.origin.y.0 as u32,
z: 0,
},
aspect: wgpu::TextureAspect::All,
},
&upload.data,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(upload.bounds.size.width.0 as u32 * bytes_per_pixel as u32),
rows_per_image: None,
},
wgpu::Extent3d {
width: upload.bounds.size.width.0 as u32,
height: upload.bounds.size.height.0 as u32,
depth_or_array_layers: 1,
},
);
}
}
}
#[derive(Default)]
struct WgpuAtlasStorage {
monochrome_textures: AtlasTextureList<WgpuAtlasTexture>,
subpixel_textures: AtlasTextureList<WgpuAtlasTexture>,
polychrome_textures: AtlasTextureList<WgpuAtlasTexture>,
monochrome_textures: AtlasTextureList<WgpuAtlasTexture>,
subpixel_textures: AtlasTextureList<WgpuAtlasTexture>,
polychrome_textures: AtlasTextureList<WgpuAtlasTexture>,
}
impl ops::Index<AtlasTextureKind> for WgpuAtlasStorage {
type Output = AtlasTextureList<WgpuAtlasTexture>;
fn index(&self, kind: AtlasTextureKind) -> &Self::Output {
match kind {
AtlasTextureKind::Monochrome => &self.monochrome_textures,
AtlasTextureKind::Subpixel => &self.subpixel_textures,
AtlasTextureKind::Polychrome => &self.polychrome_textures,
}
}
type Output = AtlasTextureList<WgpuAtlasTexture>;
fn index(&self, kind: AtlasTextureKind) -> &Self::Output {
match kind {
AtlasTextureKind::Monochrome => &self.monochrome_textures,
AtlasTextureKind::Subpixel => &self.subpixel_textures,
AtlasTextureKind::Polychrome => &self.polychrome_textures,
}
}
}
impl ops::IndexMut<AtlasTextureKind> for WgpuAtlasStorage {
fn index_mut(&mut self, kind: AtlasTextureKind) -> &mut Self::Output {
match kind {
AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
}
}
fn index_mut(&mut self, kind: AtlasTextureKind) -> &mut Self::Output {
match kind {
AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
}
}
}
impl WgpuAtlasStorage {
fn get(&self, id: AtlasTextureId) -> Option<&WgpuAtlasTexture> {
self[id.kind]
.textures
.get(id.index as usize)
.and_then(|t| t.as_ref())
}
fn get(&self, id: AtlasTextureId) -> Option<&WgpuAtlasTexture> {
self[id.kind]
.textures
.get(id.index as usize)
.and_then(|t| t.as_ref())
}
}
impl ops::Index<AtlasTextureId> for WgpuAtlasStorage {
type Output = WgpuAtlasTexture;
fn index(&self, id: AtlasTextureId) -> &Self::Output {
let textures = match id.kind {
AtlasTextureKind::Monochrome => &self.monochrome_textures,
AtlasTextureKind::Subpixel => &self.subpixel_textures,
AtlasTextureKind::Polychrome => &self.polychrome_textures,
};
textures[id.index as usize]
.as_ref()
.expect("texture must exist")
}
type Output = WgpuAtlasTexture;
fn index(&self, id: AtlasTextureId) -> &Self::Output {
let textures = match id.kind {
AtlasTextureKind::Monochrome => &self.monochrome_textures,
AtlasTextureKind::Subpixel => &self.subpixel_textures,
AtlasTextureKind::Polychrome => &self.polychrome_textures,
};
textures[id.index as usize]
.as_ref()
.expect("texture must exist")
}
}
struct WgpuAtlasTexture {
id: AtlasTextureId,
allocator: BucketedAtlasAllocator,
texture: wgpu::Texture,
view: wgpu::TextureView,
format: wgpu::TextureFormat,
live_atlas_keys: u32,
id: AtlasTextureId,
allocator: BucketedAtlasAllocator,
texture: wgpu::Texture,
view: wgpu::TextureView,
format: wgpu::TextureFormat,
live_atlas_keys: u32,
}
impl WgpuAtlasTexture {
fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
let allocation = self.allocator.allocate(device_size_to_etagere(size))?;
let tile = AtlasTile {
texture_id: self.id,
tile_id: allocation.id.into(),
padding: 0,
bounds: Bounds {
origin: etagere_point_to_device(allocation.rectangle.min),
size,
},
};
self.live_atlas_keys += 1;
Some(tile)
}
fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
let allocation = self.allocator.allocate(device_size_to_etagere(size))?;
let tile = AtlasTile {
texture_id: self.id,
tile_id: allocation.id.into(),
padding: 0,
bounds: Bounds {
origin: etagere_point_to_device(allocation.rectangle.min),
size,
},
};
self.live_atlas_keys += 1;
Some(tile)
}
fn bytes_per_pixel(&self) -> u8 {
match self.format {
wgpu::TextureFormat::R8Unorm => 1,
wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm => 4,
_ => 4,
}
}
fn bytes_per_pixel(&self) -> u8 {
match self.format {
wgpu::TextureFormat::R8Unorm => 1,
wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm => 4,
_ => 4,
}
}
fn decrement_ref_count(&mut self) {
self.live_atlas_keys -= 1;
}
fn decrement_ref_count(&mut self) {
self.live_atlas_keys -= 1;
}
fn is_unreferenced(&self) -> bool {
self.live_atlas_keys == 0
}
fn is_unreferenced(&self) -> bool {
self.live_atlas_keys == 0
}
}
fn swizzle_upload_data(bytes: &[u8], format: wgpu::TextureFormat) -> Vec<u8> {
match format {
wgpu::TextureFormat::Rgba8Unorm => {
let mut data = bytes.to_vec();
for pixel in data.chunks_exact_mut(4) {
pixel.swap(0, 2);
}
data
}
_ => bytes.to_vec(),
}
match format {
wgpu::TextureFormat::Rgba8Unorm => {
let mut data = bytes.to_vec();
for pixel in data.chunks_exact_mut(4) {
pixel.swap(0, 2);
}
data
}
_ => bytes.to_vec(),
}
}
#[cfg(all(test, not(target_family = "wasm")))]
mod tests {
use super::*;
use gpui::block_on;
use gpui::{ImageId, RenderImageParams};
use std::sync::Arc;
use super::*;
use gpui::block_on;
use gpui::{ImageId, RenderImageParams};
use std::sync::Arc;
fn test_device_and_queue() -> anyhow::Result<(Arc<wgpu::Device>, Arc<wgpu::Queue>)> {
block_on(async {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
flags: wgpu::InstanceFlags::default(),
backend_options: wgpu::BackendOptions::default(),
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
display: None,
});
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::LowPower,
compatible_surface: None,
force_fallback_adapter: false,
})
.await
.map_err(|error| anyhow::anyhow!("failed to request adapter: {error}"))?;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("wgpu_atlas_test_device"),
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::downlevel_defaults()
.using_resolution(adapter.limits())
.using_alignment(adapter.limits()),
memory_hints: wgpu::MemoryHints::MemoryUsage,
trace: wgpu::Trace::Off,
experimental_features: wgpu::ExperimentalFeatures::disabled(),
})
.await
.map_err(|error| anyhow::anyhow!("failed to request device: {error}"))?;
Ok((Arc::new(device), Arc::new(queue)))
})
}
fn test_device_and_queue() -> anyhow::Result<(Arc<wgpu::Device>, Arc<wgpu::Queue>)> {
block_on(async {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
flags: wgpu::InstanceFlags::default(),
backend_options: wgpu::BackendOptions::default(),
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
display: None,
});
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::LowPower,
compatible_surface: None,
force_fallback_adapter: false,
})
.await
.map_err(|error| anyhow::anyhow!("failed to request adapter: {error}"))?;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("wgpu_atlas_test_device"),
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::downlevel_defaults()
.using_resolution(adapter.limits())
.using_alignment(adapter.limits()),
memory_hints: wgpu::MemoryHints::MemoryUsage,
trace: wgpu::Trace::Off,
experimental_features: wgpu::ExperimentalFeatures::disabled(),
})
.await
.map_err(|error| anyhow::anyhow!("failed to request device: {error}"))?;
Ok((Arc::new(device), Arc::new(queue)))
})
}
#[test]
fn before_frame_skips_uploads_for_removed_texture() -> anyhow::Result<()> {
let (device, queue) = test_device_and_queue()?;
#[test]
fn before_frame_skips_uploads_for_removed_texture() -> anyhow::Result<()> {
let (device, queue) = test_device_and_queue()?;
let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm);
let key = AtlasKey::Image(RenderImageParams {
image_id: ImageId(1),
frame_index: 0,
});
let size = Size {
width: DevicePixels(1),
height: DevicePixels(1),
};
let mut build = || Ok(Some((size, Cow::Owned(vec![0, 0, 0, 255]))));
let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm);
let key = AtlasKey::Image(RenderImageParams {
image_id: ImageId(1),
frame_index: 0,
});
let size = Size {
width: DevicePixels(1),
height: DevicePixels(1),
};
let mut build = || Ok(Some((size, Cow::Owned(vec![0, 0, 0, 255]))));
// Regression test: before the fix, this panicked in flush_uploads
atlas
.get_or_insert_with(&key, &mut build)?
.expect("tile should be created");
atlas.remove(&key);
atlas.before_frame();
Ok(())
}
// Regression test: before the fix, this panicked in flush_uploads
atlas
.get_or_insert_with(&key, &mut build)?
.expect("tile should be created");
atlas.remove(&key);
atlas.before_frame();
Ok(())
}
#[test]
fn swizzle_upload_data_preserves_bgra_uploads() {
let input = vec![0x10, 0x20, 0x30, 0x40];
assert_eq!(
swizzle_upload_data(&input, wgpu::TextureFormat::Bgra8Unorm),
input
);
}
#[test]
fn swizzle_upload_data_preserves_bgra_uploads() {
let input = vec![0x10, 0x20, 0x30, 0x40];
assert_eq!(
swizzle_upload_data(&input, wgpu::TextureFormat::Bgra8Unorm),
input
);
}
#[test]
fn swizzle_upload_data_converts_bgra_to_rgba() {
let input = vec![0x10, 0x20, 0x30, 0x40, 0xAA, 0xBB, 0xCC, 0xDD];
assert_eq!(
swizzle_upload_data(&input, wgpu::TextureFormat::Rgba8Unorm),
vec![0x30, 0x20, 0x10, 0x40, 0xCC, 0xBB, 0xAA, 0xDD]
);
}
#[test]
fn swizzle_upload_data_converts_bgra_to_rgba() {
let input = vec![0x10, 0x20, 0x30, 0x40, 0xAA, 0xBB, 0xCC, 0xDD];
assert_eq!(
swizzle_upload_data(&input, wgpu::TextureFormat::Rgba8Unorm),
vec![0x30, 0x20, 0x10, 0x40, 0xCC, 0xBB, 0xAA, 0xDD]
);
}
}
+431 -431
View File
@@ -7,19 +7,19 @@ use std::sync::atomic::{AtomicBool, Ordering};
use wgpu::TextureFormat;
pub struct WgpuContext {
pub instance: wgpu::Instance,
pub adapter: wgpu::Adapter,
pub device: Arc<wgpu::Device>,
pub queue: Arc<wgpu::Queue>,
dual_source_blending: bool,
color_texture_format: wgpu::TextureFormat,
device_lost: Arc<AtomicBool>,
pub instance: wgpu::Instance,
pub adapter: wgpu::Adapter,
pub device: Arc<wgpu::Device>,
pub queue: Arc<wgpu::Queue>,
dual_source_blending: bool,
color_texture_format: wgpu::TextureFormat,
device_lost: Arc<AtomicBool>,
}
#[derive(Clone, Copy)]
pub struct CompositorGpuHint {
pub vendor_id: u32,
pub device_id: u32,
pub vendor_id: u32,
pub device_id: u32,
}
/// Extra wgpu features and limits that an application can request on top of
@@ -27,495 +27,495 @@ pub struct CompositorGpuHint {
/// [`gpui::App::set_gpu_requirements`] *before* opening any windows.
#[derive(Clone, Debug, Default)]
pub struct WgpuDeviceRequirements {
/// Additional [`wgpu::Features`] to enable. These are OR-ed with gpui's
/// own required features.
pub features: wgpu::Features,
/// Additional [`wgpu::Limits`] to request. Each field is merged by taking
/// `max(gpui_limit, app_limit)` for upper-bound limits and
/// `min(gpui_limit, app_limit)` for alignment/lower-bound limits.
pub limits: wgpu::Limits,
/// Additional [`wgpu::Features`] to enable. These are OR-ed with gpui's
/// own required features.
pub features: wgpu::Features,
/// Additional [`wgpu::Limits`] to request. Each field is merged by taking
/// `max(gpui_limit, app_limit)` for upper-bound limits and
/// `min(gpui_limit, app_limit)` for alignment/lower-bound limits.
pub limits: wgpu::Limits,
}
impl WgpuContext {
#[cfg(not(target_family = "wasm"))]
pub fn new(
instance: wgpu::Instance,
surface: &wgpu::Surface<'_>,
compositor_gpu: Option<CompositorGpuHint>,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<Self> {
Self::new_with_options(instance, surface, compositor_gpu, false, extra_requirements)
}
#[cfg(not(target_family = "wasm"))]
pub fn new(
instance: wgpu::Instance,
surface: &wgpu::Surface<'_>,
compositor_gpu: Option<CompositorGpuHint>,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<Self> {
Self::new_with_options(instance, surface, compositor_gpu, false, extra_requirements)
}
#[cfg(not(target_family = "wasm"))]
pub fn new_rejecting_software(
instance: wgpu::Instance,
surface: &wgpu::Surface<'_>,
compositor_gpu: Option<CompositorGpuHint>,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<Self> {
Self::new_with_options(instance, surface, compositor_gpu, true, extra_requirements)
}
#[cfg(not(target_family = "wasm"))]
pub fn new_rejecting_software(
instance: wgpu::Instance,
surface: &wgpu::Surface<'_>,
compositor_gpu: Option<CompositorGpuHint>,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<Self> {
Self::new_with_options(instance, surface, compositor_gpu, true, extra_requirements)
}
#[cfg(not(target_family = "wasm"))]
fn new_with_options(
instance: wgpu::Instance,
surface: &wgpu::Surface<'_>,
compositor_gpu: Option<CompositorGpuHint>,
reject_software: bool,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<Self> {
let device_id_filter = match std::env::var("ZED_DEVICE_ID") {
Ok(val) => parse_pci_id(&val)
.context("Failed to parse device ID from `ZED_DEVICE_ID` environment variable")
.log_err(),
Err(std::env::VarError::NotPresent) => None,
err => {
err.context("Failed to read value of `ZED_DEVICE_ID` environment variable")
.log_err();
None
}
};
#[cfg(not(target_family = "wasm"))]
fn new_with_options(
instance: wgpu::Instance,
surface: &wgpu::Surface<'_>,
compositor_gpu: Option<CompositorGpuHint>,
reject_software: bool,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<Self> {
let device_id_filter = match std::env::var("ZED_DEVICE_ID") {
Ok(val) => parse_pci_id(&val)
.context("Failed to parse device ID from `ZED_DEVICE_ID` environment variable")
.log_err(),
Err(std::env::VarError::NotPresent) => None,
err => {
err.context("Failed to read value of `ZED_DEVICE_ID` environment variable")
.log_err();
None
}
};
// Select an adapter by actually testing surface configuration with the real device.
// This is the only reliable way to determine compatibility on hybrid GPU systems.
let (adapter, device, queue, dual_source_blending, color_texture_format) =
gpui::block_on(Self::select_adapter_and_device(
&instance,
device_id_filter,
surface,
compositor_gpu.as_ref(),
reject_software,
extra_requirements,
))?;
// Select an adapter by actually testing surface configuration with the real device.
// This is the only reliable way to determine compatibility on hybrid GPU systems.
let (adapter, device, queue, dual_source_blending, color_texture_format) =
gpui::block_on(Self::select_adapter_and_device(
&instance,
device_id_filter,
surface,
compositor_gpu.as_ref(),
reject_software,
extra_requirements,
))?;
let device_lost = Arc::new(AtomicBool::new(false));
device.set_device_lost_callback({
let device_lost = Arc::clone(&device_lost);
move |reason, message| {
log::error!("wgpu device lost: reason={reason:?}, message={message}");
if reason != wgpu::DeviceLostReason::Destroyed {
device_lost.store(true, Ordering::Relaxed);
}
}
});
let device_lost = Arc::new(AtomicBool::new(false));
device.set_device_lost_callback({
let device_lost = Arc::clone(&device_lost);
move |reason, message| {
log::error!("wgpu device lost: reason={reason:?}, message={message}");
if reason != wgpu::DeviceLostReason::Destroyed {
device_lost.store(true, Ordering::Relaxed);
}
}
});
log::info!(
"Selected GPU adapter: {:?} ({:?})",
adapter.get_info().name,
adapter.get_info().backend
);
log::info!(
"Selected GPU adapter: {:?} ({:?})",
adapter.get_info().name,
adapter.get_info().backend
);
Ok(Self {
instance,
adapter,
device: Arc::new(device),
queue: Arc::new(queue),
dual_source_blending,
color_texture_format,
device_lost,
})
}
Ok(Self {
instance,
adapter,
device: Arc::new(device),
queue: Arc::new(queue),
dual_source_blending,
color_texture_format,
device_lost,
})
}
#[cfg(target_family = "wasm")]
pub async fn new_web() -> anyhow::Result<Self> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL,
flags: wgpu::InstanceFlags::default(),
backend_options: wgpu::BackendOptions::default(),
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
display: None,
});
#[cfg(target_family = "wasm")]
pub async fn new_web() -> anyhow::Result<Self> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL,
flags: wgpu::InstanceFlags::default(),
backend_options: wgpu::BackendOptions::default(),
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
display: None,
});
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: None,
force_fallback_adapter: false,
})
.await
.map_err(|e| anyhow::anyhow!("Failed to request GPU adapter: {e}"))?;
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: None,
force_fallback_adapter: false,
})
.await
.map_err(|e| anyhow::anyhow!("Failed to request GPU adapter: {e}"))?;
log::info!(
"Selected GPU adapter: {:?} ({:?})",
adapter.get_info().name,
adapter.get_info().backend
);
log::info!(
"Selected GPU adapter: {:?} ({:?})",
adapter.get_info().name,
adapter.get_info().backend
);
let device_lost = Arc::new(AtomicBool::new(false));
let (device, queue, dual_source_blending, color_texture_format) =
Self::create_device(&adapter, None).await?;
let device_lost = Arc::new(AtomicBool::new(false));
let (device, queue, dual_source_blending, color_texture_format) =
Self::create_device(&adapter, None).await?;
Ok(Self {
instance,
adapter,
device: Arc::new(device),
queue: Arc::new(queue),
dual_source_blending,
color_texture_format,
device_lost,
})
}
Ok(Self {
instance,
adapter,
device: Arc::new(device),
queue: Arc::new(queue),
dual_source_blending,
color_texture_format,
device_lost,
})
}
async fn create_device(
adapter: &wgpu::Adapter,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool, TextureFormat)> {
let dual_source_blending = adapter
.features()
.contains(wgpu::Features::DUAL_SOURCE_BLENDING);
async fn create_device(
adapter: &wgpu::Adapter,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool, TextureFormat)> {
let dual_source_blending = adapter
.features()
.contains(wgpu::Features::DUAL_SOURCE_BLENDING);
let mut required_features = wgpu::Features::empty();
if dual_source_blending {
required_features |= wgpu::Features::DUAL_SOURCE_BLENDING;
} else {
log::warn!(
"Dual-source blending not available on this GPU. \
let mut required_features = wgpu::Features::empty();
if dual_source_blending {
required_features |= wgpu::Features::DUAL_SOURCE_BLENDING;
} else {
log::warn!(
"Dual-source blending not available on this GPU. \
Subpixel text antialiasing will be disabled."
);
}
);
}
let color_atlas_texture_format = Self::select_color_texture_format(adapter)?;
let color_atlas_texture_format = Self::select_color_texture_format(adapter)?;
let mut required_limits = wgpu::Limits::downlevel_defaults()
.using_resolution(adapter.limits())
.using_alignment(adapter.limits());
let mut required_limits = wgpu::Limits::downlevel_defaults()
.using_resolution(adapter.limits())
.using_alignment(adapter.limits());
// Merge application-requested requirements.
if let Some(reqs) = extra_requirements {
required_features |= reqs.features;
required_limits = required_limits.or_better_values_from(&reqs.limits);
}
// Merge application-requested requirements.
if let Some(reqs) = extra_requirements {
required_features |= reqs.features;
required_limits = required_limits.or_better_values_from(&reqs.limits);
}
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("gpui_device"),
required_features,
required_limits,
memory_hints: wgpu::MemoryHints::MemoryUsage,
trace: wgpu::Trace::Off,
experimental_features: wgpu::ExperimentalFeatures::disabled(),
})
.await
.map_err(|e| anyhow::anyhow!("Failed to create wgpu device: {e}"))?;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: Some("gpui_device"),
required_features,
required_limits,
memory_hints: wgpu::MemoryHints::MemoryUsage,
trace: wgpu::Trace::Off,
experimental_features: wgpu::ExperimentalFeatures::disabled(),
})
.await
.map_err(|e| anyhow::anyhow!("Failed to create wgpu device: {e}"))?;
Ok((
device,
queue,
dual_source_blending,
color_atlas_texture_format,
))
}
Ok((
device,
queue,
dual_source_blending,
color_atlas_texture_format,
))
}
#[cfg(not(target_family = "wasm"))]
pub fn instance(display: Box<dyn wgpu::wgt::WgpuHasDisplayHandle>) -> wgpu::Instance {
#[cfg(not(target_os = "windows"))]
let backends = wgpu::Backends::VULKAN | wgpu::Backends::GL;
#[cfg(target_os = "windows")]
let backends = wgpu::Backends::DX12;
#[cfg(not(target_family = "wasm"))]
pub fn instance(display: Box<dyn wgpu::wgt::WgpuHasDisplayHandle>) -> wgpu::Instance {
#[cfg(not(target_os = "windows"))]
let backends = wgpu::Backends::VULKAN | wgpu::Backends::GL;
#[cfg(target_os = "windows")]
let backends = wgpu::Backends::DX12;
wgpu::Instance::new(wgpu::InstanceDescriptor {
backends,
flags: wgpu::InstanceFlags::default(),
backend_options: wgpu::BackendOptions::default(),
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
display: Some(display),
})
}
wgpu::Instance::new(wgpu::InstanceDescriptor {
backends,
flags: wgpu::InstanceFlags::default(),
backend_options: wgpu::BackendOptions::default(),
memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
display: Some(display),
})
}
pub fn check_compatible_with_surface(&self, surface: &wgpu::Surface<'_>) -> anyhow::Result<()> {
let caps = surface.get_capabilities(&self.adapter);
if caps.formats.is_empty() {
let info = self.adapter.get_info();
anyhow::bail!(
"Adapter {:?} (backend={:?}, device={:#06x}) is not compatible with the \
pub fn check_compatible_with_surface(&self, surface: &wgpu::Surface<'_>) -> anyhow::Result<()> {
let caps = surface.get_capabilities(&self.adapter);
if caps.formats.is_empty() {
let info = self.adapter.get_info();
anyhow::bail!(
"Adapter {:?} (backend={:?}, device={:#06x}) is not compatible with the \
display surface for this window.",
info.name,
info.backend,
info.device,
);
}
Ok(())
}
info.name,
info.backend,
info.device,
);
}
Ok(())
}
/// Select an adapter and create a device, testing that the surface can actually be configured.
/// This is the only reliable way to determine compatibility on hybrid GPU systems, where
/// adapters may report surface compatibility via get_capabilities() but fail when actually
/// configuring (e.g., NVIDIA reporting Vulkan Wayland support but failing because the
/// Wayland compositor runs on the Intel GPU).
#[cfg(not(target_family = "wasm"))]
async fn select_adapter_and_device(
instance: &wgpu::Instance,
device_id_filter: Option<u32>,
surface: &wgpu::Surface<'_>,
compositor_gpu: Option<&CompositorGpuHint>,
reject_software: bool,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<(
wgpu::Adapter,
wgpu::Device,
wgpu::Queue,
bool,
TextureFormat,
)> {
let mut adapters: Vec<_> = instance.enumerate_adapters(wgpu::Backends::all()).await;
/// Select an adapter and create a device, testing that the surface can actually be configured.
/// This is the only reliable way to determine compatibility on hybrid GPU systems, where
/// adapters may report surface compatibility via get_capabilities() but fail when actually
/// configuring (e.g., NVIDIA reporting Vulkan Wayland support but failing because the
/// Wayland compositor runs on the Intel GPU).
#[cfg(not(target_family = "wasm"))]
async fn select_adapter_and_device(
instance: &wgpu::Instance,
device_id_filter: Option<u32>,
surface: &wgpu::Surface<'_>,
compositor_gpu: Option<&CompositorGpuHint>,
reject_software: bool,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<(
wgpu::Adapter,
wgpu::Device,
wgpu::Queue,
bool,
TextureFormat,
)> {
let mut adapters: Vec<_> = instance.enumerate_adapters(wgpu::Backends::all()).await;
if adapters.is_empty() {
anyhow::bail!("No GPU adapters found");
}
if adapters.is_empty() {
anyhow::bail!("No GPU adapters found");
}
if let Some(device_id) = device_id_filter {
log::info!("ZED_DEVICE_ID filter: {:#06x}", device_id);
}
if let Some(device_id) = device_id_filter {
log::info!("ZED_DEVICE_ID filter: {:#06x}", device_id);
}
// Sort adapters into a single priority order. Tiers (from highest to lowest):
//
// 1. ZED_DEVICE_ID match — explicit user override
// 2. Compositor GPU match — the GPU the display server is rendering on
// 3. Device type (Discrete > Integrated > Other > Virtual > Cpu).
// "Other" ranks above "Virtual" because OpenGL seems to count as "Other".
// 4. Backend — prefer Vulkan/Metal/Dx12 over GL/etc.
adapters.sort_by_key(|adapter| {
let info = adapter.get_info();
// Sort adapters into a single priority order. Tiers (from highest to lowest):
//
// 1. ZED_DEVICE_ID match — explicit user override
// 2. Compositor GPU match — the GPU the display server is rendering on
// 3. Device type (Discrete > Integrated > Other > Virtual > Cpu).
// "Other" ranks above "Virtual" because OpenGL seems to count as "Other".
// 4. Backend — prefer Vulkan/Metal/Dx12 over GL/etc.
adapters.sort_by_key(|adapter| {
let info = adapter.get_info();
// Backends like OpenGL report device=0 for all adapters, so
// device-based matching is only meaningful when non-zero.
let device_known = info.device != 0;
// Backends like OpenGL report device=0 for all adapters, so
// device-based matching is only meaningful when non-zero.
let device_known = info.device != 0;
let user_override: u8 = match device_id_filter {
Some(id) if device_known && info.device == id => 0,
_ => 1,
};
let user_override: u8 = match device_id_filter {
Some(id) if device_known && info.device == id => 0,
_ => 1,
};
let compositor_match: u8 = match compositor_gpu {
Some(hint)
if device_known
&& info.vendor == hint.vendor_id
&& info.device == hint.device_id =>
{
0
}
_ => 1,
};
let compositor_match: u8 = match compositor_gpu {
Some(hint)
if device_known
&& info.vendor == hint.vendor_id
&& info.device == hint.device_id =>
{
0
}
_ => 1,
};
let type_priority: u8 = if info.device_type == wgpu::DeviceType::Cpu {
4
} else {
match info.device_type {
wgpu::DeviceType::DiscreteGpu => 0,
wgpu::DeviceType::IntegratedGpu => 1,
wgpu::DeviceType::Other => 2,
wgpu::DeviceType::VirtualGpu => 3,
wgpu::DeviceType::Cpu => 4,
}
};
let type_priority: u8 = if info.device_type == wgpu::DeviceType::Cpu {
4
} else {
match info.device_type {
wgpu::DeviceType::DiscreteGpu => 0,
wgpu::DeviceType::IntegratedGpu => 1,
wgpu::DeviceType::Other => 2,
wgpu::DeviceType::VirtualGpu => 3,
wgpu::DeviceType::Cpu => 4,
}
};
let backend_priority: u8 = match info.backend {
wgpu::Backend::Vulkan | wgpu::Backend::Metal | wgpu::Backend::Dx12 => 0,
_ => 1,
};
let backend_priority: u8 = match info.backend {
wgpu::Backend::Vulkan | wgpu::Backend::Metal | wgpu::Backend::Dx12 => 0,
_ => 1,
};
(
user_override,
compositor_match,
type_priority,
backend_priority,
)
});
(
user_override,
compositor_match,
type_priority,
backend_priority,
)
});
// Log all available adapters (in sorted order)
log::info!("Found {} GPU adapter(s):", adapters.len());
for adapter in &adapters {
let info = adapter.get_info();
log::info!(
" - {} (vendor={:#06x}, device={:#06x}, backend={:?}, type={:?})",
info.name,
info.vendor,
info.device,
info.backend,
info.device_type,
);
}
// Log all available adapters (in sorted order)
log::info!("Found {} GPU adapter(s):", adapters.len());
for adapter in &adapters {
let info = adapter.get_info();
log::info!(
" - {} (vendor={:#06x}, device={:#06x}, backend={:?}, type={:?})",
info.name,
info.vendor,
info.device,
info.backend,
info.device_type,
);
}
// Test each adapter by creating a device and configuring the surface
for adapter in adapters {
let info = adapter.get_info();
// Test each adapter by creating a device and configuring the surface
for adapter in adapters {
let info = adapter.get_info();
if reject_software && info.device_type == wgpu::DeviceType::Cpu {
log::info!(
"Skipping software renderer: {} ({:?})",
info.name,
info.backend
);
continue;
}
if reject_software && info.device_type == wgpu::DeviceType::Cpu {
log::info!(
"Skipping software renderer: {} ({:?})",
info.name,
info.backend
);
continue;
}
log::info!("Testing adapter: {} ({:?})...", info.name, info.backend);
log::info!("Testing adapter: {} ({:?})...", info.name, info.backend);
match Self::try_adapter_with_surface(&adapter, surface, extra_requirements).await {
Ok((device, queue, dual_source_blending, color_atlas_texture_format)) => {
log::info!(
"Selected GPU (passed configuration test): {} ({:?})",
info.name,
info.backend
);
return Ok((
adapter,
device,
queue,
dual_source_blending,
color_atlas_texture_format,
));
}
Err(e) => {
log::info!(
" Adapter {} ({:?}) failed: {}, trying next...",
info.name,
info.backend,
e
);
}
}
}
match Self::try_adapter_with_surface(&adapter, surface, extra_requirements).await {
Ok((device, queue, dual_source_blending, color_atlas_texture_format)) => {
log::info!(
"Selected GPU (passed configuration test): {} ({:?})",
info.name,
info.backend
);
return Ok((
adapter,
device,
queue,
dual_source_blending,
color_atlas_texture_format,
));
}
Err(e) => {
log::info!(
" Adapter {} ({:?}) failed: {}, trying next...",
info.name,
info.backend,
e
);
}
}
}
anyhow::bail!("No GPU adapter found that can configure the display surface")
}
anyhow::bail!("No GPU adapter found that can configure the display surface")
}
/// Try to use an adapter with a surface by creating a device and testing configuration.
/// Returns the device and queue if successful, allowing them to be reused.
#[cfg(not(target_family = "wasm"))]
async fn try_adapter_with_surface(
adapter: &wgpu::Adapter,
surface: &wgpu::Surface<'_>,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool, TextureFormat)> {
let caps = surface.get_capabilities(adapter);
if caps.formats.is_empty() {
anyhow::bail!("no compatible surface formats");
}
if caps.alpha_modes.is_empty() {
anyhow::bail!("no compatible alpha modes");
}
/// Try to use an adapter with a surface by creating a device and testing configuration.
/// Returns the device and queue if successful, allowing them to be reused.
#[cfg(not(target_family = "wasm"))]
async fn try_adapter_with_surface(
adapter: &wgpu::Adapter,
surface: &wgpu::Surface<'_>,
extra_requirements: Option<&WgpuDeviceRequirements>,
) -> anyhow::Result<(wgpu::Device, wgpu::Queue, bool, TextureFormat)> {
let caps = surface.get_capabilities(adapter);
if caps.formats.is_empty() {
anyhow::bail!("no compatible surface formats");
}
if caps.alpha_modes.is_empty() {
anyhow::bail!("no compatible alpha modes");
}
let (device, queue, dual_source_blending, color_atlas_texture_format) =
Self::create_device(adapter, extra_requirements).await?;
let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
let (device, queue, dual_source_blending, color_atlas_texture_format) =
Self::create_device(adapter, extra_requirements).await?;
let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
let test_config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: caps.formats[0],
width: 64,
height: 64,
present_mode: wgpu::PresentMode::Fifo,
desired_maximum_frame_latency: 2,
alpha_mode: caps.alpha_modes[0],
view_formats: vec![],
};
let test_config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: caps.formats[0],
width: 64,
height: 64,
present_mode: wgpu::PresentMode::Fifo,
desired_maximum_frame_latency: 2,
alpha_mode: caps.alpha_modes[0],
view_formats: vec![],
};
surface.configure(&device, &test_config);
surface.configure(&device, &test_config);
let error = error_scope.pop().await;
if let Some(e) = error {
anyhow::bail!("surface configuration failed: {e}");
}
let error = error_scope.pop().await;
if let Some(e) = error {
anyhow::bail!("surface configuration failed: {e}");
}
Ok((
device,
queue,
dual_source_blending,
color_atlas_texture_format,
))
}
Ok((
device,
queue,
dual_source_blending,
color_atlas_texture_format,
))
}
fn select_color_texture_format(adapter: &wgpu::Adapter) -> anyhow::Result<wgpu::TextureFormat> {
let required_usages = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST;
let bgra_features = adapter.get_texture_format_features(wgpu::TextureFormat::Bgra8Unorm);
if bgra_features.allowed_usages.contains(required_usages) {
return Ok(wgpu::TextureFormat::Bgra8Unorm);
}
fn select_color_texture_format(adapter: &wgpu::Adapter) -> anyhow::Result<wgpu::TextureFormat> {
let required_usages = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST;
let bgra_features = adapter.get_texture_format_features(wgpu::TextureFormat::Bgra8Unorm);
if bgra_features.allowed_usages.contains(required_usages) {
return Ok(wgpu::TextureFormat::Bgra8Unorm);
}
let rgba_features = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba8Unorm);
if rgba_features.allowed_usages.contains(required_usages) {
let info = adapter.get_info();
log::warn!(
"Adapter {} ({:?}) does not support Bgra8Unorm atlas textures with usages {:?}; \
let rgba_features = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba8Unorm);
if rgba_features.allowed_usages.contains(required_usages) {
let info = adapter.get_info();
log::warn!(
"Adapter {} ({:?}) does not support Bgra8Unorm atlas textures with usages {:?}; \
falling back to Rgba8Unorm atlas textures.",
info.name,
info.backend,
required_usages,
);
return Ok(wgpu::TextureFormat::Rgba8Unorm);
}
info.name,
info.backend,
required_usages,
);
return Ok(wgpu::TextureFormat::Rgba8Unorm);
}
let info = adapter.get_info();
Err(anyhow::anyhow!(
"Adapter {} ({:?}, device={:#06x}) does not support a usable color atlas texture \
let info = adapter.get_info();
Err(anyhow::anyhow!(
"Adapter {} ({:?}, device={:#06x}) does not support a usable color atlas texture \
format with usages {:?}. Bgra8Unorm allowed usages: {:?}; \
Rgba8Unorm allowed usages: {:?}.",
info.name,
info.backend,
info.device,
required_usages,
bgra_features.allowed_usages,
rgba_features.allowed_usages,
))
}
pub fn supports_dual_source_blending(&self) -> bool {
self.dual_source_blending
}
info.name,
info.backend,
info.device,
required_usages,
bgra_features.allowed_usages,
rgba_features.allowed_usages,
))
}
pub fn supports_dual_source_blending(&self) -> bool {
self.dual_source_blending
}
pub fn color_texture_format(&self) -> wgpu::TextureFormat {
self.color_texture_format
}
pub fn color_texture_format(&self) -> wgpu::TextureFormat {
self.color_texture_format
}
/// Returns true if the GPU device was lost (e.g., due to driver crash, suspend/resume).
/// When this returns true, the context should be recreated.
pub fn device_lost(&self) -> bool {
self.device_lost.load(Ordering::Relaxed)
}
/// Returns true if the GPU device was lost (e.g., due to driver crash, suspend/resume).
/// When this returns true, the context should be recreated.
pub fn device_lost(&self) -> bool {
self.device_lost.load(Ordering::Relaxed)
}
/// Returns a clone of the device_lost flag for sharing with renderers.
pub(crate) fn device_lost_flag(&self) -> Arc<AtomicBool> {
Arc::clone(&self.device_lost)
}
/// Returns a clone of the device_lost flag for sharing with renderers.
pub(crate) fn device_lost_flag(&self) -> Arc<AtomicBool> {
Arc::clone(&self.device_lost)
}
}
#[cfg(not(target_family = "wasm"))]
fn parse_pci_id(id: &str) -> anyhow::Result<u32> {
let mut id = id.trim();
let mut id = id.trim();
if id.starts_with("0x") || id.starts_with("0X") {
id = &id[2..];
}
let is_hex_string = id.chars().all(|c| c.is_ascii_hexdigit());
let is_4_chars = id.len() == 4;
anyhow::ensure!(
is_4_chars && is_hex_string,
"Expected a 4 digit PCI ID in hexadecimal format"
);
if id.starts_with("0x") || id.starts_with("0X") {
id = &id[2..];
}
let is_hex_string = id.chars().all(|c| c.is_ascii_hexdigit());
let is_4_chars = id.len() == 4;
anyhow::ensure!(
is_4_chars && is_hex_string,
"Expected a 4 digit PCI ID in hexadecimal format"
);
u32::from_str_radix(id, 16).context("parsing PCI ID as hex")
u32::from_str_radix(id, 16).context("parsing PCI ID as hex")
}
#[cfg(test)]
mod tests {
use super::parse_pci_id;
use super::parse_pci_id;
#[test]
fn test_parse_device_id() {
assert!(parse_pci_id("0xABCD").is_ok());
assert!(parse_pci_id("ABCD").is_ok());
assert!(parse_pci_id("abcd").is_ok());
assert!(parse_pci_id("1234").is_ok());
assert!(parse_pci_id("123").is_err());
assert_eq!(
parse_pci_id(&format!("{:x}", 0x1234)).unwrap(),
parse_pci_id(&format!("{:X}", 0x1234)).unwrap(),
);
#[test]
fn test_parse_device_id() {
assert!(parse_pci_id("0xABCD").is_ok());
assert!(parse_pci_id("ABCD").is_ok());
assert!(parse_pci_id("abcd").is_ok());
assert!(parse_pci_id("1234").is_ok());
assert!(parse_pci_id("123").is_err());
assert_eq!(
parse_pci_id(&format!("{:x}", 0x1234)).unwrap(),
parse_pci_id(&format!("{:X}", 0x1234)).unwrap(),
);
assert_eq!(
parse_pci_id(&format!("{:#x}", 0x1234)).unwrap(),
parse_pci_id(&format!("{:#X}", 0x1234)).unwrap(),
);
}
assert_eq!(
parse_pci_id(&format!("{:#x}", 0x1234)).unwrap(),
parse_pci_id(&format!("{:#X}", 0x1234)).unwrap(),
);
}
}
File diff suppressed because it is too large Load Diff