Enable Blade on MacOS via "macos-blade" feature (#7669)

Depends on https://github.com/zed-industries/font-kit/pull/2 and
https://github.com/kvark/blade/pull/77

This change enables Blade to be also used on MacOS. It will also make it
easier to use it on Windows.

What works: most of the things. Zed loads as fast and appears equally
responsive to the current renderer.
<img width="306" alt="Screenshot 2024-02-11 at 12 09 15 AM"
src="https://github.com/zed-industries/zed/assets/107301/66d82f45-5ea2-4e2b-86c6-5b3ed333c827">

Things missing:
- [x] video streaming. ~~Requires a bit of plumbing on both Blade and
Zed sides, but all fairly straightforward.~~
  -  verified with a local setup
- [x] resize. ~~Not sure where exactly to hook up the reaction on the
window size change. Once we know where, the fix is one line.~~
- [ ] fine-tune CA Layer
- this isn't a blocker for merging the PR, but it would be a blocker if
we wanted to switch to the new path by default
- [ ] rebase on latest, get the dependency merged (need review/merge of
https://github.com/zed-industries/font-kit/pull/2!)

Update: I implemented resize support as well as "surface" rendering on
the Blade path (which will be useful on Linux/Windows later on). I
haven't tested the latter though - not sure how to get something
streaming. Would appreciate some help! I don't think this should be a
blocker to this PR, anyway.

The only little piece that's missing for the Blade on MacOS path to be
full-featured is fine-tuning the CALayer configuration. Zed does a lot
of careful logic in configuring the layer, such as switching the
"present with transaction" on/off intermittently, which Blade path
doesn't have yet.

Release Notes:
- N/A

---------

Co-authored-by: Mikayla <mikayla@zed.dev>
This commit is contained in:
Dzmitry Malyshau
2024-02-16 13:39:40 -08:00
committed by GitHub
co-authored by Mikayla
parent 1c361ac579
commit 9ad1862f2f
23 changed files with 492 additions and 163 deletions
@@ -1,361 +0,0 @@
use super::{BladeBelt, BladeBeltDescriptor};
use crate::{
AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, DevicePixels, PlatformAtlas,
Point, Size,
};
use anyhow::Result;
use blade_graphics as gpu;
use collections::FxHashMap;
use etagere::BucketedAtlasAllocator;
use parking_lot::Mutex;
use std::{borrow::Cow, ops, sync::Arc};
pub(crate) const PATH_TEXTURE_FORMAT: gpu::TextureFormat = gpu::TextureFormat::R16Float;
pub(crate) struct BladeAtlas(Mutex<BladeAtlasState>);
struct PendingUpload {
id: AtlasTextureId,
bounds: Bounds<DevicePixels>,
data: gpu::BufferPiece,
}
struct BladeAtlasState {
gpu: Arc<gpu::Context>,
upload_belt: BladeBelt,
storage: BladeAtlasStorage,
tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
initializations: Vec<AtlasTextureId>,
uploads: Vec<PendingUpload>,
}
impl BladeAtlasState {
fn destroy(&mut self) {
self.storage.destroy(&self.gpu);
self.upload_belt.destroy(&self.gpu);
}
}
pub struct BladeTextureInfo {
pub size: gpu::Extent,
pub raw_view: gpu::TextureView,
}
impl BladeAtlas {
pub(crate) fn new(gpu: &Arc<gpu::Context>) -> Self {
BladeAtlas(Mutex::new(BladeAtlasState {
gpu: Arc::clone(gpu),
upload_belt: BladeBelt::new(BladeBeltDescriptor {
memory: gpu::Memory::Upload,
min_chunk_size: 0x10000,
alignment: 64, // Vulkan `optimalBufferCopyOffsetAlignment` on Intel XE
}),
storage: BladeAtlasStorage::default(),
tiles_by_key: Default::default(),
initializations: Vec::new(),
uploads: Vec::new(),
}))
}
pub(crate) fn destroy(&self) {
self.0.lock().destroy();
}
pub(crate) fn clear_textures(&self, texture_kind: AtlasTextureKind) {
let mut lock = self.0.lock();
let textures = &mut lock.storage[texture_kind];
for texture in textures {
texture.clear();
}
}
pub fn allocate(&self, size: Size<DevicePixels>, texture_kind: AtlasTextureKind) -> AtlasTile {
let mut lock = self.0.lock();
lock.allocate(size, texture_kind)
}
pub fn before_frame(&self, gpu_encoder: &mut gpu::CommandEncoder) {
let mut lock = self.0.lock();
lock.flush(gpu_encoder);
}
pub fn after_frame(&self, sync_point: &gpu::SyncPoint) {
let mut lock = self.0.lock();
lock.upload_belt.flush(sync_point);
}
pub fn get_texture_info(&self, id: AtlasTextureId) -> BladeTextureInfo {
let lock = self.0.lock();
let texture = &lock.storage[id];
let size = texture.allocator.size();
BladeTextureInfo {
size: gpu::Extent {
width: size.width as u32,
height: size.height as u32,
depth: 1,
},
raw_view: texture.raw_view,
}
}
}
impl PlatformAtlas for BladeAtlas {
fn get_or_insert_with<'a>(
&self,
key: &AtlasKey,
build: &mut dyn FnMut() -> Result<(Size<DevicePixels>, Cow<'a, [u8]>)>,
) -> Result<AtlasTile> {
let mut lock = self.0.lock();
if let Some(tile) = lock.tiles_by_key.get(key) {
Ok(tile.clone())
} else {
let (size, bytes) = build()?;
let tile = lock.allocate(size, key.texture_kind());
lock.upload_texture(tile.texture_id, tile.bounds, &bytes);
lock.tiles_by_key.insert(key.clone(), tile.clone());
Ok(tile)
}
}
}
impl BladeAtlasState {
fn allocate(&mut self, size: Size<DevicePixels>, texture_kind: AtlasTextureKind) -> AtlasTile {
let textures = &mut self.storage[texture_kind];
textures
.iter_mut()
.rev()
.find_map(|texture| texture.allocate(size))
.unwrap_or_else(|| {
let texture = self.push_texture(size, texture_kind);
texture.allocate(size).unwrap()
})
}
fn push_texture(
&mut self,
min_size: Size<DevicePixels>,
kind: AtlasTextureKind,
) -> &mut BladeAtlasTexture {
const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
width: DevicePixels(1024),
height: DevicePixels(1024),
};
let size = min_size.max(&DEFAULT_ATLAS_SIZE);
let format;
let usage;
match kind {
AtlasTextureKind::Monochrome => {
format = gpu::TextureFormat::R8Unorm;
usage = gpu::TextureUsage::COPY | gpu::TextureUsage::RESOURCE;
}
AtlasTextureKind::Polychrome => {
format = gpu::TextureFormat::Bgra8Unorm;
usage = gpu::TextureUsage::COPY | gpu::TextureUsage::RESOURCE;
}
AtlasTextureKind::Path => {
format = PATH_TEXTURE_FORMAT;
usage = gpu::TextureUsage::COPY
| gpu::TextureUsage::RESOURCE
| gpu::TextureUsage::TARGET;
}
}
let raw = self.gpu.create_texture(gpu::TextureDesc {
name: "atlas",
format,
size: gpu::Extent {
width: size.width.into(),
height: size.height.into(),
depth: 1,
},
array_layer_count: 1,
mip_level_count: 1,
dimension: gpu::TextureDimension::D2,
usage,
});
let raw_view = self.gpu.create_texture_view(gpu::TextureViewDesc {
name: "",
texture: raw,
format,
dimension: gpu::ViewDimension::D2,
subresources: &Default::default(),
});
let textures = &mut self.storage[kind];
let atlas_texture = BladeAtlasTexture {
id: AtlasTextureId {
index: textures.len() as u32,
kind,
},
allocator: etagere::BucketedAtlasAllocator::new(size.into()),
format,
raw,
raw_view,
};
self.initializations.push(atlas_texture.id);
textures.push(atlas_texture);
textures.last_mut().unwrap()
}
fn upload_texture(&mut self, id: AtlasTextureId, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
let data = unsafe { self.upload_belt.alloc_data(bytes, &self.gpu) };
self.uploads.push(PendingUpload { id, bounds, data });
}
fn flush(&mut self, encoder: &mut gpu::CommandEncoder) {
for id in self.initializations.drain(..) {
let texture = &self.storage[id];
encoder.init_texture(texture.raw);
}
let mut transfers = encoder.transfer();
for upload in self.uploads.drain(..) {
let texture = &self.storage[upload.id];
transfers.copy_buffer_to_texture(
upload.data,
upload.bounds.size.width.to_bytes(texture.bytes_per_pixel()),
gpu::TexturePiece {
texture: texture.raw,
mip_level: 0,
array_layer: 0,
origin: [
upload.bounds.origin.x.into(),
upload.bounds.origin.y.into(),
0,
],
},
gpu::Extent {
width: upload.bounds.size.width.into(),
height: upload.bounds.size.height.into(),
depth: 1,
},
);
}
}
}
#[derive(Default)]
struct BladeAtlasStorage {
monochrome_textures: Vec<BladeAtlasTexture>,
polychrome_textures: Vec<BladeAtlasTexture>,
path_textures: Vec<BladeAtlasTexture>,
}
impl ops::Index<AtlasTextureKind> for BladeAtlasStorage {
type Output = Vec<BladeAtlasTexture>;
fn index(&self, kind: AtlasTextureKind) -> &Self::Output {
match kind {
crate::AtlasTextureKind::Monochrome => &self.monochrome_textures,
crate::AtlasTextureKind::Polychrome => &self.polychrome_textures,
crate::AtlasTextureKind::Path => &self.path_textures,
}
}
}
impl ops::IndexMut<AtlasTextureKind> for BladeAtlasStorage {
fn index_mut(&mut self, kind: AtlasTextureKind) -> &mut Self::Output {
match kind {
crate::AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
crate::AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
crate::AtlasTextureKind::Path => &mut self.path_textures,
}
}
}
impl ops::Index<AtlasTextureId> for BladeAtlasStorage {
type Output = BladeAtlasTexture;
fn index(&self, id: AtlasTextureId) -> &Self::Output {
let textures = match id.kind {
crate::AtlasTextureKind::Monochrome => &self.monochrome_textures,
crate::AtlasTextureKind::Polychrome => &self.polychrome_textures,
crate::AtlasTextureKind::Path => &self.path_textures,
};
&textures[id.index as usize]
}
}
impl BladeAtlasStorage {
fn destroy(&mut self, gpu: &gpu::Context) {
for mut texture in self.monochrome_textures.drain(..) {
texture.destroy(gpu);
}
for mut texture in self.polychrome_textures.drain(..) {
texture.destroy(gpu);
}
for mut texture in self.path_textures.drain(..) {
texture.destroy(gpu);
}
}
}
struct BladeAtlasTexture {
id: AtlasTextureId,
allocator: BucketedAtlasAllocator,
raw: gpu::Texture,
raw_view: gpu::TextureView,
format: gpu::TextureFormat,
}
impl BladeAtlasTexture {
fn clear(&mut self) {
self.allocator.clear();
}
fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
let allocation = self.allocator.allocate(size.into())?;
let tile = AtlasTile {
texture_id: self.id,
tile_id: allocation.id.into(),
padding: 0,
bounds: Bounds {
origin: allocation.rectangle.min.into(),
size,
},
};
Some(tile)
}
fn destroy(&mut self, gpu: &gpu::Context) {
gpu.destroy_texture(self.raw);
gpu.destroy_texture_view(self.raw_view);
}
fn bytes_per_pixel(&self) -> u8 {
self.format.block_info().size
}
}
impl From<Size<DevicePixels>> for etagere::Size {
fn from(size: Size<DevicePixels>) -> Self {
etagere::Size::new(size.width.into(), size.height.into())
}
}
impl From<etagere::Point> for Point<DevicePixels> {
fn from(value: etagere::Point) -> Self {
Point {
x: DevicePixels::from(value.x),
y: DevicePixels::from(value.y),
}
}
}
impl From<etagere::Size> for Size<DevicePixels> {
fn from(size: etagere::Size) -> Self {
Size {
width: DevicePixels::from(size.width),
height: DevicePixels::from(size.height),
}
}
}
impl From<etagere::Rectangle> for Bounds<DevicePixels> {
fn from(rectangle: etagere::Rectangle) -> Self {
Bounds {
origin: rectangle.min.into(),
size: rectangle.size().into(),
}
}
}
@@ -1,100 +0,0 @@
use blade_graphics as gpu;
use std::mem;
struct ReusableBuffer {
raw: gpu::Buffer,
size: u64,
}
pub struct BladeBeltDescriptor {
pub memory: gpu::Memory,
pub min_chunk_size: u64,
pub alignment: u64,
}
/// A belt of buffers, used by the BladeAtlas to cheaply
/// find staging space for uploads.
pub struct BladeBelt {
desc: BladeBeltDescriptor,
buffers: Vec<(ReusableBuffer, gpu::SyncPoint)>,
active: Vec<(ReusableBuffer, u64)>,
}
impl BladeBelt {
pub fn new(desc: BladeBeltDescriptor) -> Self {
assert_ne!(desc.alignment, 0);
Self {
desc,
buffers: Vec::new(),
active: Vec::new(),
}
}
pub fn destroy(&mut self, gpu: &gpu::Context) {
for (buffer, _) in self.buffers.drain(..) {
gpu.destroy_buffer(buffer.raw);
}
for (buffer, _) in self.active.drain(..) {
gpu.destroy_buffer(buffer.raw);
}
}
pub fn alloc(&mut self, size: u64, gpu: &gpu::Context) -> gpu::BufferPiece {
for &mut (ref rb, ref mut offset) in self.active.iter_mut() {
let aligned = offset.next_multiple_of(self.desc.alignment);
if aligned + size <= rb.size {
let piece = rb.raw.at(aligned);
*offset = aligned + size;
return piece;
}
}
let index_maybe = self
.buffers
.iter()
.position(|(rb, sp)| size <= rb.size && gpu.wait_for(sp, 0));
if let Some(index) = index_maybe {
let (rb, _) = self.buffers.remove(index);
let piece = rb.raw.into();
self.active.push((rb, size));
return piece;
}
let chunk_index = self.buffers.len() + self.active.len();
let chunk_size = size.max(self.desc.min_chunk_size);
let chunk = gpu.create_buffer(gpu::BufferDesc {
name: &format!("chunk-{}", chunk_index),
size: chunk_size,
memory: self.desc.memory,
});
let rb = ReusableBuffer {
raw: chunk,
size: chunk_size,
};
self.active.push((rb, size));
chunk.into()
}
// SAFETY: T should be zeroable and ordinary data, no references, pointers, cells or other complicated data type.
pub unsafe fn alloc_data<T>(&mut self, data: &[T], gpu: &gpu::Context) -> gpu::BufferPiece {
assert!(!data.is_empty());
let type_alignment = mem::align_of::<T>() as u64;
debug_assert_eq!(
self.desc.alignment % type_alignment,
0,
"Type alignment {} is too big",
type_alignment
);
let total_bytes = std::mem::size_of_val(data);
let bp = self.alloc(total_bytes as u64, gpu);
unsafe {
std::ptr::copy_nonoverlapping(data.as_ptr() as *const u8, bp.data(), total_bytes);
}
bp
}
pub fn flush(&mut self, sp: &gpu::SyncPoint) {
self.buffers
.extend(self.active.drain(..).map(|(rb, _)| (rb, sp.clone())));
}
}
@@ -1,515 +0,0 @@
// Doing `if let` gives you nice scoping with passes/encoders
#![allow(irrefutable_let_patterns)]
use super::{BladeBelt, BladeBeltDescriptor};
use crate::{
AtlasTextureKind, AtlasTile, BladeAtlas, Bounds, ContentMask, Hsla, MonochromeSprite, Path,
PathId, PathVertex, PolychromeSprite, PrimitiveBatch, Quad, ScaledPixels, Scene, Shadow,
Underline, PATH_TEXTURE_FORMAT,
};
use bytemuck::{Pod, Zeroable};
use collections::HashMap;
use blade_graphics as gpu;
use std::{mem, sync::Arc};
const SURFACE_FRAME_COUNT: u32 = 3;
const MAX_FRAME_TIME_MS: u32 = 1000;
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct GlobalParams {
viewport_size: [f32; 2],
pad: [u32; 2],
}
#[derive(blade_macros::ShaderData)]
struct ShaderQuadsData {
globals: GlobalParams,
b_quads: gpu::BufferPiece,
}
#[derive(blade_macros::ShaderData)]
struct ShaderShadowsData {
globals: GlobalParams,
b_shadows: gpu::BufferPiece,
}
#[derive(blade_macros::ShaderData)]
struct ShaderPathRasterizationData {
globals: GlobalParams,
b_path_vertices: gpu::BufferPiece,
}
#[derive(blade_macros::ShaderData)]
struct ShaderPathsData {
globals: GlobalParams,
t_sprite: gpu::TextureView,
s_sprite: gpu::Sampler,
b_path_sprites: gpu::BufferPiece,
}
#[derive(blade_macros::ShaderData)]
struct ShaderUnderlinesData {
globals: GlobalParams,
b_underlines: gpu::BufferPiece,
}
#[derive(blade_macros::ShaderData)]
struct ShaderMonoSpritesData {
globals: GlobalParams,
t_sprite: gpu::TextureView,
s_sprite: gpu::Sampler,
b_mono_sprites: gpu::BufferPiece,
}
#[derive(blade_macros::ShaderData)]
struct ShaderPolySpritesData {
globals: GlobalParams,
t_sprite: gpu::TextureView,
s_sprite: gpu::Sampler,
b_poly_sprites: gpu::BufferPiece,
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[repr(C)]
struct PathSprite {
bounds: Bounds<ScaledPixels>,
color: Hsla,
tile: AtlasTile,
}
struct BladePipelines {
quads: gpu::RenderPipeline,
shadows: gpu::RenderPipeline,
path_rasterization: gpu::RenderPipeline,
paths: gpu::RenderPipeline,
underlines: gpu::RenderPipeline,
mono_sprites: gpu::RenderPipeline,
poly_sprites: gpu::RenderPipeline,
}
impl BladePipelines {
fn new(gpu: &gpu::Context, surface_format: gpu::TextureFormat) -> Self {
use gpu::ShaderData as _;
let shader = gpu.create_shader(gpu::ShaderDesc {
source: include_str!("shaders.wgsl"),
});
shader.check_struct_size::<Quad>();
shader.check_struct_size::<Shadow>();
assert_eq!(
mem::size_of::<PathVertex<ScaledPixels>>(),
shader.get_struct_size("PathVertex") as usize,
);
shader.check_struct_size::<PathSprite>();
shader.check_struct_size::<Underline>();
shader.check_struct_size::<MonochromeSprite>();
shader.check_struct_size::<PolychromeSprite>();
Self {
quads: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
name: "quads",
data_layouts: &[&ShaderQuadsData::layout()],
vertex: shader.at("vs_quad"),
primitive: gpu::PrimitiveState {
topology: gpu::PrimitiveTopology::TriangleStrip,
..Default::default()
},
depth_stencil: None,
fragment: shader.at("fs_quad"),
color_targets: &[gpu::ColorTargetState {
format: surface_format,
blend: Some(gpu::BlendState::ALPHA_BLENDING),
write_mask: gpu::ColorWrites::default(),
}],
}),
shadows: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
name: "shadows",
data_layouts: &[&ShaderShadowsData::layout()],
vertex: shader.at("vs_shadow"),
primitive: gpu::PrimitiveState {
topology: gpu::PrimitiveTopology::TriangleStrip,
..Default::default()
},
depth_stencil: None,
fragment: shader.at("fs_shadow"),
color_targets: &[gpu::ColorTargetState {
format: surface_format,
blend: Some(gpu::BlendState::ALPHA_BLENDING),
write_mask: gpu::ColorWrites::default(),
}],
}),
path_rasterization: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
name: "path_rasterization",
data_layouts: &[&ShaderPathRasterizationData::layout()],
vertex: shader.at("vs_path_rasterization"),
primitive: gpu::PrimitiveState {
topology: gpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil: None,
fragment: shader.at("fs_path_rasterization"),
color_targets: &[gpu::ColorTargetState {
format: PATH_TEXTURE_FORMAT,
blend: Some(gpu::BlendState::ADDITIVE),
write_mask: gpu::ColorWrites::default(),
}],
}),
paths: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
name: "paths",
data_layouts: &[&ShaderPathsData::layout()],
vertex: shader.at("vs_path"),
primitive: gpu::PrimitiveState {
topology: gpu::PrimitiveTopology::TriangleStrip,
..Default::default()
},
depth_stencil: None,
fragment: shader.at("fs_path"),
color_targets: &[gpu::ColorTargetState {
format: surface_format,
blend: Some(gpu::BlendState::ALPHA_BLENDING),
write_mask: gpu::ColorWrites::default(),
}],
}),
underlines: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
name: "underlines",
data_layouts: &[&ShaderUnderlinesData::layout()],
vertex: shader.at("vs_underline"),
primitive: gpu::PrimitiveState {
topology: gpu::PrimitiveTopology::TriangleStrip,
..Default::default()
},
depth_stencil: None,
fragment: shader.at("fs_underline"),
color_targets: &[gpu::ColorTargetState {
format: surface_format,
blend: Some(gpu::BlendState::ALPHA_BLENDING),
write_mask: gpu::ColorWrites::default(),
}],
}),
mono_sprites: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
name: "mono-sprites",
data_layouts: &[&ShaderMonoSpritesData::layout()],
vertex: shader.at("vs_mono_sprite"),
primitive: gpu::PrimitiveState {
topology: gpu::PrimitiveTopology::TriangleStrip,
..Default::default()
},
depth_stencil: None,
fragment: shader.at("fs_mono_sprite"),
color_targets: &[gpu::ColorTargetState {
format: surface_format,
blend: Some(gpu::BlendState::ALPHA_BLENDING),
write_mask: gpu::ColorWrites::default(),
}],
}),
poly_sprites: gpu.create_render_pipeline(gpu::RenderPipelineDesc {
name: "poly-sprites",
data_layouts: &[&ShaderPolySpritesData::layout()],
vertex: shader.at("vs_poly_sprite"),
primitive: gpu::PrimitiveState {
topology: gpu::PrimitiveTopology::TriangleStrip,
..Default::default()
},
depth_stencil: None,
fragment: shader.at("fs_poly_sprite"),
color_targets: &[gpu::ColorTargetState {
format: surface_format,
blend: Some(gpu::BlendState::ALPHA_BLENDING),
write_mask: gpu::ColorWrites::default(),
}],
}),
}
}
}
pub struct BladeRenderer {
gpu: Arc<gpu::Context>,
command_encoder: gpu::CommandEncoder,
last_sync_point: Option<gpu::SyncPoint>,
pipelines: BladePipelines,
instance_belt: BladeBelt,
viewport_size: gpu::Extent,
path_tiles: HashMap<PathId, AtlasTile>,
atlas: Arc<BladeAtlas>,
atlas_sampler: gpu::Sampler,
}
impl BladeRenderer {
fn make_surface_config(size: gpu::Extent) -> gpu::SurfaceConfig {
gpu::SurfaceConfig {
size,
usage: gpu::TextureUsage::TARGET,
frame_count: SURFACE_FRAME_COUNT,
//Note: this matches the original logic of the Metal backend,
// but ultimaterly we need to switch to `Linear`.
color_space: gpu::ColorSpace::Srgb,
}
}
pub fn new(gpu: Arc<gpu::Context>, size: gpu::Extent) -> Self {
let surface_format = gpu.resize(Self::make_surface_config(size));
let command_encoder = gpu.create_command_encoder(gpu::CommandEncoderDesc {
name: "main",
buffer_count: 2,
});
let pipelines = BladePipelines::new(&gpu, surface_format);
let instance_belt = BladeBelt::new(BladeBeltDescriptor {
memory: gpu::Memory::Shared,
min_chunk_size: 0x1000,
alignment: 0x40, // Vulkan `minStorageBufferOffsetAlignment` on Intel Xe
});
let atlas = Arc::new(BladeAtlas::new(&gpu));
let atlas_sampler = gpu.create_sampler(gpu::SamplerDesc {
name: "atlas",
mag_filter: gpu::FilterMode::Linear,
min_filter: gpu::FilterMode::Linear,
..Default::default()
});
Self {
gpu,
command_encoder,
last_sync_point: None,
pipelines,
instance_belt,
viewport_size: size,
path_tiles: HashMap::default(),
atlas,
atlas_sampler,
}
}
fn wait_for_gpu(&mut self) {
if let Some(last_sp) = self.last_sync_point.take() {
if !self.gpu.wait_for(&last_sp, MAX_FRAME_TIME_MS) {
panic!("GPU hung");
}
}
}
pub fn destroy(&mut self) {
self.wait_for_gpu();
self.atlas.destroy();
self.instance_belt.destroy(&self.gpu);
self.gpu.destroy_command_encoder(&mut self.command_encoder);
}
pub fn resize(&mut self, size: gpu::Extent) {
self.wait_for_gpu();
self.gpu.resize(Self::make_surface_config(size));
self.viewport_size = size;
}
pub fn viewport_size(&self) -> gpu::Extent {
self.viewport_size
}
pub fn atlas(&self) -> &Arc<BladeAtlas> {
&self.atlas
}
fn rasterize_paths(&mut self, paths: &[Path<ScaledPixels>]) {
self.path_tiles.clear();
let mut vertices_by_texture_id = HashMap::default();
for path in paths {
let clipped_bounds = path.bounds.intersect(&path.content_mask.bounds);
let tile = self
.atlas
.allocate(clipped_bounds.size.map(Into::into), AtlasTextureKind::Path);
vertices_by_texture_id
.entry(tile.texture_id)
.or_insert(Vec::new())
.extend(path.vertices.iter().map(|vertex| PathVertex {
xy_position: vertex.xy_position - clipped_bounds.origin
+ tile.bounds.origin.map(Into::into),
st_position: vertex.st_position,
content_mask: ContentMask {
bounds: tile.bounds.map(Into::into),
},
}));
self.path_tiles.insert(path.id, tile);
}
for (texture_id, vertices) in vertices_by_texture_id {
let tex_info = self.atlas.get_texture_info(texture_id);
let globals = GlobalParams {
viewport_size: [tex_info.size.width as f32, tex_info.size.height as f32],
pad: [0; 2],
};
let vertex_buf = unsafe { self.instance_belt.alloc_data(&vertices, &self.gpu) };
let mut pass = self.command_encoder.render(gpu::RenderTargetSet {
colors: &[gpu::RenderTarget {
view: tex_info.raw_view,
init_op: gpu::InitOp::Clear(gpu::TextureColor::OpaqueBlack),
finish_op: gpu::FinishOp::Store,
}],
depth_stencil: None,
});
let mut encoder = pass.with(&self.pipelines.path_rasterization);
encoder.bind(
0,
&ShaderPathRasterizationData {
globals,
b_path_vertices: vertex_buf,
},
);
encoder.draw(0, vertices.len() as u32, 0, 1);
}
}
pub fn draw(&mut self, scene: &Scene) {
let frame = self.gpu.acquire_frame();
self.command_encoder.start();
self.command_encoder.init_texture(frame.texture());
self.atlas.before_frame(&mut self.command_encoder);
self.rasterize_paths(scene.paths());
let globals = GlobalParams {
viewport_size: [
self.viewport_size.width as f32,
self.viewport_size.height as f32,
],
pad: [0; 2],
};
if let mut pass = self.command_encoder.render(gpu::RenderTargetSet {
colors: &[gpu::RenderTarget {
view: frame.texture_view(),
init_op: gpu::InitOp::Clear(gpu::TextureColor::TransparentBlack),
finish_op: gpu::FinishOp::Store,
}],
depth_stencil: None,
}) {
for batch in scene.batches() {
match batch {
PrimitiveBatch::Quads(quads) => {
let instance_buf =
unsafe { self.instance_belt.alloc_data(quads, &self.gpu) };
let mut encoder = pass.with(&self.pipelines.quads);
encoder.bind(
0,
&ShaderQuadsData {
globals,
b_quads: instance_buf,
},
);
encoder.draw(0, 4, 0, quads.len() as u32);
}
PrimitiveBatch::Shadows(shadows) => {
let instance_buf =
unsafe { self.instance_belt.alloc_data(shadows, &self.gpu) };
let mut encoder = pass.with(&self.pipelines.shadows);
encoder.bind(
0,
&ShaderShadowsData {
globals,
b_shadows: instance_buf,
},
);
encoder.draw(0, 4, 0, shadows.len() as u32);
}
PrimitiveBatch::Paths(paths) => {
let mut encoder = pass.with(&self.pipelines.paths);
//todo!(linux): group by texture ID
for path in paths {
let tile = &self.path_tiles[&path.id];
let tex_info = self.atlas.get_texture_info(tile.texture_id);
let origin = path.bounds.intersect(&path.content_mask.bounds).origin;
let sprites = [PathSprite {
bounds: Bounds {
origin: origin.map(|p| p.floor()),
size: tile.bounds.size.map(Into::into),
},
color: path.color,
tile: (*tile).clone(),
}];
let instance_buf =
unsafe { self.instance_belt.alloc_data(&sprites, &self.gpu) };
encoder.bind(
0,
&ShaderPathsData {
globals,
t_sprite: tex_info.raw_view,
s_sprite: self.atlas_sampler,
b_path_sprites: instance_buf,
},
);
encoder.draw(0, 4, 0, sprites.len() as u32);
}
}
PrimitiveBatch::Underlines(underlines) => {
let instance_buf =
unsafe { self.instance_belt.alloc_data(underlines, &self.gpu) };
let mut encoder = pass.with(&self.pipelines.underlines);
encoder.bind(
0,
&ShaderUnderlinesData {
globals,
b_underlines: instance_buf,
},
);
encoder.draw(0, 4, 0, underlines.len() as u32);
}
PrimitiveBatch::MonochromeSprites {
texture_id,
sprites,
} => {
let tex_info = self.atlas.get_texture_info(texture_id);
let instance_buf =
unsafe { self.instance_belt.alloc_data(sprites, &self.gpu) };
let mut encoder = pass.with(&self.pipelines.mono_sprites);
encoder.bind(
0,
&ShaderMonoSpritesData {
globals,
t_sprite: tex_info.raw_view,
s_sprite: self.atlas_sampler,
b_mono_sprites: instance_buf,
},
);
encoder.draw(0, 4, 0, sprites.len() as u32);
}
PrimitiveBatch::PolychromeSprites {
texture_id,
sprites,
} => {
let tex_info = self.atlas.get_texture_info(texture_id);
let instance_buf =
unsafe { self.instance_belt.alloc_data(sprites, &self.gpu) };
let mut encoder = pass.with(&self.pipelines.poly_sprites);
encoder.bind(
0,
&ShaderPolySpritesData {
globals,
t_sprite: tex_info.raw_view,
s_sprite: self.atlas_sampler,
b_poly_sprites: instance_buf,
},
);
encoder.draw(0, 4, 0, sprites.len() as u32);
}
PrimitiveBatch::Surfaces { .. } => {
unimplemented!()
}
}
}
}
self.command_encoder.present(frame);
let sync_point = self.gpu.submit(&mut self.command_encoder);
self.instance_belt.flush(&sync_point);
self.atlas.after_frame(&sync_point);
self.atlas.clear_textures(AtlasTextureKind::Path);
self.wait_for_gpu();
self.last_sync_point = Some(sync_point);
}
}
-569
View File
@@ -1,569 +0,0 @@
struct Globals {
viewport_size: vec2<f32>,
pad: vec2<u32>,
}
var<uniform> globals: Globals;
var t_sprite: texture_2d<f32>;
var s_sprite: sampler;
const M_PI_F: f32 = 3.1415926;
const GRAYSCALE_FACTORS: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722);
struct ViewId {
lo: u32,
hi: u32,
}
struct Bounds {
origin: vec2<f32>,
size: vec2<f32>,
}
struct Corners {
top_left: f32,
top_right: f32,
bottom_right: f32,
bottom_left: f32,
}
struct Edges {
top: f32,
right: f32,
bottom: f32,
left: f32,
}
struct Hsla {
h: f32,
s: f32,
l: f32,
a: f32,
}
struct AtlasTextureId {
index: u32,
kind: u32,
}
struct AtlasBounds {
origin: vec2<i32>,
size: vec2<i32>,
}
struct AtlasTile {
texture_id: AtlasTextureId,
tile_id: u32,
padding: u32,
bounds: AtlasBounds,
}
fn to_device_position_impl(position: vec2<f32>) -> vec4<f32> {
let device_position = position / globals.viewport_size * vec2<f32>(2.0, -2.0) + vec2<f32>(-1.0, 1.0);
return vec4<f32>(device_position, 0.0, 1.0);
}
fn to_device_position(unit_vertex: vec2<f32>, bounds: Bounds) -> vec4<f32> {
let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
return to_device_position_impl(position);
}
fn to_tile_position(unit_vertex: vec2<f32>, tile: AtlasTile) -> vec2<f32> {
let atlas_size = vec2<f32>(textureDimensions(t_sprite, 0));
return (vec2<f32>(tile.bounds.origin) + unit_vertex * vec2<f32>(tile.bounds.size)) / atlas_size;
}
fn distance_from_clip_rect_impl(position: vec2<f32>, clip_bounds: Bounds) -> vec4<f32> {
let tl = position - clip_bounds.origin;
let br = clip_bounds.origin + clip_bounds.size - position;
return vec4<f32>(tl.x, br.x, tl.y, br.y);
}
fn distance_from_clip_rect(unit_vertex: vec2<f32>, bounds: Bounds, clip_bounds: Bounds) -> vec4<f32> {
let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
return distance_from_clip_rect_impl(position, clip_bounds);
}
fn hsla_to_rgba(hsla: Hsla) -> vec4<f32> {
let h = hsla.h * 6.0; // Now, it's an angle but scaled in [0, 6) range
let s = hsla.s;
let l = hsla.l;
let a = hsla.a;
let c = (1.0 - abs(2.0 * l - 1.0)) * s;
let x = c * (1.0 - abs(h % 2.0 - 1.0));
let m = l - c / 2.0;
var color = vec4<f32>(m, m, m, a);
if (h >= 0.0 && h < 1.0) {
color.r += c;
color.g += x;
} else if (h >= 1.0 && h < 2.0) {
color.r += x;
color.g += c;
} else if (h >= 2.0 && h < 3.0) {
color.g += c;
color.b += x;
} else if (h >= 3.0 && h < 4.0) {
color.g += x;
color.b += c;
} else if (h >= 4.0 && h < 5.0) {
color.r += x;
color.b += c;
} else {
color.r += c;
color.b += x;
}
return color;
}
fn over(below: vec4<f32>, above: vec4<f32>) -> vec4<f32> {
let alpha = above.a + below.a * (1.0 - above.a);
let color = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha;
return vec4<f32>(color, alpha);
}
// A standard gaussian function, used for weighting samples
fn gaussian(x: f32, sigma: f32) -> f32{
return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * M_PI_F) * sigma);
}
// This approximates the error function, needed for the gaussian integral
fn erf(v: vec2<f32>) -> vec2<f32> {
let s = sign(v);
let a = abs(v);
let r1 = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
let r2 = r1 * r1;
return s - s / (r2 * r2);
}
fn blur_along_x(x: f32, y: f32, sigma: f32, corner: f32, half_size: vec2<f32>) -> f32 {
let delta = min(half_size.y - corner - abs(y), 0.0);
let curved = half_size.x - corner + sqrt(max(0.0, corner * corner - delta * delta));
let integral = 0.5 + 0.5 * erf((x + vec2<f32>(-curved, curved)) * (sqrt(0.5) / sigma));
return integral.y - integral.x;
}
fn pick_corner_radius(point: vec2<f32>, radii: Corners) -> f32 {
if (point.x < 0.0) {
if (point.y < 0.0) {
return radii.top_left;
} else {
return radii.bottom_left;
}
} else {
if (point.y < 0.0) {
return radii.top_right;
} else {
return radii.bottom_right;
}
}
}
fn quad_sdf(point: vec2<f32>, bounds: Bounds, corner_radii: Corners) -> f32 {
let half_size = bounds.size / 2.0;
let center = bounds.origin + half_size;
let center_to_point = point - center;
let corner_radius = pick_corner_radius(center_to_point, corner_radii);
let rounded_edge_to_point = abs(center_to_point) - half_size + corner_radius;
return length(max(vec2<f32>(0.0), rounded_edge_to_point)) +
min(0.0, max(rounded_edge_to_point.x, rounded_edge_to_point.y)) -
corner_radius;
}
// --- quads --- //
struct Quad {
view_id: ViewId,
layer_id: u32,
order: u32,
bounds: Bounds,
content_mask: Bounds,
background: Hsla,
border_color: Hsla,
corner_radii: Corners,
border_widths: Edges,
}
var<storage, read> b_quads: array<Quad>;
struct QuadVarying {
@builtin(position) position: vec4<f32>,
@location(0) @interpolate(flat) background_color: vec4<f32>,
@location(1) @interpolate(flat) border_color: vec4<f32>,
@location(2) @interpolate(flat) quad_id: u32,
//TODO: use `clip_distance` once Naga supports it
@location(3) clip_distances: vec4<f32>,
}
@vertex
fn vs_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> QuadVarying {
let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
let quad = b_quads[instance_id];
var out = QuadVarying();
out.position = to_device_position(unit_vertex, quad.bounds);
out.background_color = hsla_to_rgba(quad.background);
out.border_color = hsla_to_rgba(quad.border_color);
out.quad_id = instance_id;
out.clip_distances = distance_from_clip_rect(unit_vertex, quad.bounds, quad.content_mask);
return out;
}
@fragment
fn fs_quad(input: QuadVarying) -> @location(0) vec4<f32> {
// Alpha clip first, since we don't have `clip_distance`.
if (any(input.clip_distances < vec4<f32>(0.0))) {
return vec4<f32>(0.0);
}
let quad = b_quads[input.quad_id];
let half_size = quad.bounds.size / 2.0;
let center = quad.bounds.origin + half_size;
let center_to_point = input.position.xy - center;
let corner_radius = pick_corner_radius(center_to_point, quad.corner_radii);
let rounded_edge_to_point = abs(center_to_point) - half_size + corner_radius;
let distance =
length(max(vec2<f32>(0.0), rounded_edge_to_point)) +
min(0.0, max(rounded_edge_to_point.x, rounded_edge_to_point.y)) -
corner_radius;
let vertical_border = select(quad.border_widths.left, quad.border_widths.right, center_to_point.x > 0.0);
let horizontal_border = select(quad.border_widths.top, quad.border_widths.bottom, center_to_point.y > 0.0);
let inset_size = half_size - corner_radius - vec2<f32>(vertical_border, horizontal_border);
let point_to_inset_corner = abs(center_to_point) - inset_size;
var border_width = 0.0;
if (point_to_inset_corner.x < 0.0 && point_to_inset_corner.y < 0.0) {
border_width = 0.0;
} else if (point_to_inset_corner.y > point_to_inset_corner.x) {
border_width = horizontal_border;
} else {
border_width = vertical_border;
}
var color = input.background_color;
if (border_width > 0.0) {
let inset_distance = distance + border_width;
// Blend the border on top of the background and then linearly interpolate
// between the two as we slide inside the background.
let blended_border = over(input.background_color, input.border_color);
color = mix(blended_border, input.background_color,
saturate(0.5 - inset_distance));
}
return color * vec4<f32>(1.0, 1.0, 1.0, saturate(0.5 - distance));
}
// --- shadows --- //
struct Shadow {
view_id: ViewId,
layer_id: u32,
order: u32,
bounds: Bounds,
corner_radii: Corners,
content_mask: Bounds,
color: Hsla,
blur_radius: f32,
pad: u32,
}
var<storage, read> b_shadows: array<Shadow>;
struct ShadowVarying {
@builtin(position) position: vec4<f32>,
@location(0) @interpolate(flat) color: vec4<f32>,
@location(1) @interpolate(flat) shadow_id: u32,
//TODO: use `clip_distance` once Naga supports it
@location(3) clip_distances: vec4<f32>,
}
@vertex
fn vs_shadow(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> ShadowVarying {
let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
var shadow = b_shadows[instance_id];
let margin = 3.0 * shadow.blur_radius;
// Set the bounds of the shadow and adjust its size based on the shadow's
// spread radius to achieve the spreading effect
shadow.bounds.origin -= vec2<f32>(margin);
shadow.bounds.size += 2.0 * vec2<f32>(margin);
var out = ShadowVarying();
out.position = to_device_position(unit_vertex, shadow.bounds);
out.color = hsla_to_rgba(shadow.color);
out.shadow_id = instance_id;
out.clip_distances = distance_from_clip_rect(unit_vertex, shadow.bounds, shadow.content_mask);
return out;
}
@fragment
fn fs_shadow(input: ShadowVarying) -> @location(0) vec4<f32> {
// Alpha clip first, since we don't have `clip_distance`.
if (any(input.clip_distances < vec4<f32>(0.0))) {
return vec4<f32>(0.0);
}
let shadow = b_shadows[input.shadow_id];
let half_size = shadow.bounds.size / 2.0;
let center = shadow.bounds.origin + half_size;
let center_to_point = input.position.xy - center;
let corner_radius = pick_corner_radius(center_to_point, shadow.corner_radii);
// The signal is only non-zero in a limited range, so don't waste samples
let low = center_to_point.y - half_size.y;
let high = center_to_point.y + half_size.y;
let start = clamp(-3.0 * shadow.blur_radius, low, high);
let end = clamp(3.0 * shadow.blur_radius, low, high);
// Accumulate samples (we can get away with surprisingly few samples)
let step = (end - start) / 4.0;
var y = start + step * 0.5;
var alpha = 0.0;
for (var i = 0; i < 4; i += 1) {
let blur = blur_along_x(center_to_point.x, center_to_point.y - y,
shadow.blur_radius, corner_radius, half_size);
alpha += blur * gaussian(y, shadow.blur_radius) * step;
y += step;
}
return input.color * vec4<f32>(1.0, 1.0, 1.0, alpha);
}
// --- path rasterization --- //
struct PathVertex {
xy_position: vec2<f32>,
st_position: vec2<f32>,
content_mask: Bounds,
}
var<storage, read> b_path_vertices: array<PathVertex>;
struct PathRasterizationVarying {
@builtin(position) position: vec4<f32>,
@location(0) st_position: vec2<f32>,
//TODO: use `clip_distance` once Naga supports it
@location(3) clip_distances: vec4<f32>,
}
@vertex
fn vs_path_rasterization(@builtin(vertex_index) vertex_id: u32) -> PathRasterizationVarying {
let v = b_path_vertices[vertex_id];
var out = PathRasterizationVarying();
out.position = to_device_position_impl(v.xy_position);
out.st_position = v.st_position;
out.clip_distances = distance_from_clip_rect_impl(v.xy_position, v.content_mask);
return out;
}
@fragment
fn fs_path_rasterization(input: PathRasterizationVarying) -> @location(0) f32 {
let dx = dpdx(input.st_position);
let dy = dpdy(input.st_position);
if (any(input.clip_distances < vec4<f32>(0.0))) {
return 0.0;
}
let gradient = 2.0 * input.st_position.xx * vec2<f32>(dx.x, dy.x) - vec2<f32>(dx.y, dy.y);
let f = input.st_position.x * input.st_position.x - input.st_position.y;
let distance = f / length(gradient);
return saturate(0.5 - distance);
}
// --- paths --- //
struct PathSprite {
bounds: Bounds,
color: Hsla,
tile: AtlasTile,
}
var<storage, read> b_path_sprites: array<PathSprite>;
struct PathVarying {
@builtin(position) position: vec4<f32>,
@location(0) tile_position: vec2<f32>,
@location(1) color: vec4<f32>,
}
@vertex
fn vs_path(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PathVarying {
let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
let sprite = b_path_sprites[instance_id];
// Don't apply content mask because it was already accounted for when rasterizing the path.
var out = PathVarying();
out.position = to_device_position(unit_vertex, sprite.bounds);
out.tile_position = to_tile_position(unit_vertex, sprite.tile);
out.color = hsla_to_rgba(sprite.color);
return out;
}
@fragment
fn fs_path(input: PathVarying) -> @location(0) vec4<f32> {
let sample = textureSample(t_sprite, s_sprite, input.tile_position).r;
let mask = 1.0 - abs(1.0 - sample % 2.0);
return input.color * mask;
}
// --- underlines --- //
struct Underline {
view_id: ViewId,
layer_id: u32,
order: u32,
bounds: Bounds,
content_mask: Bounds,
color: Hsla,
thickness: f32,
wavy: u32,
}
var<storage, read> b_underlines: array<Underline>;
struct UnderlineVarying {
@builtin(position) position: vec4<f32>,
@location(0) @interpolate(flat) color: vec4<f32>,
@location(1) @interpolate(flat) underline_id: u32,
//TODO: use `clip_distance` once Naga supports it
@location(3) clip_distances: vec4<f32>,
}
@vertex
fn vs_underline(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> UnderlineVarying {
let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
let underline = b_underlines[instance_id];
var out = UnderlineVarying();
out.position = to_device_position(unit_vertex, underline.bounds);
out.color = hsla_to_rgba(underline.color);
out.underline_id = instance_id;
out.clip_distances = distance_from_clip_rect(unit_vertex, underline.bounds, underline.content_mask);
return out;
}
@fragment
fn fs_underline(input: UnderlineVarying) -> @location(0) vec4<f32> {
// Alpha clip first, since we don't have `clip_distance`.
if (any(input.clip_distances < vec4<f32>(0.0))) {
return vec4<f32>(0.0);
}
let underline = b_underlines[input.underline_id];
if ((underline.wavy & 0xFFu) == 0u)
{
return vec4<f32>(0.0);
}
let half_thickness = underline.thickness * 0.5;
let st = (input.position.xy - underline.bounds.origin) / underline.bounds.size.y - vec2<f32>(0.0, 0.5);
let frequency = M_PI_F * 3.0 * underline.thickness / 8.0;
let amplitude = 1.0 / (2.0 * underline.thickness);
let sine = sin(st.x * frequency) * amplitude;
let dSine = cos(st.x * frequency) * amplitude * frequency;
let distance = (st.y - sine) / sqrt(1.0 + dSine * dSine);
let distance_in_pixels = distance * underline.bounds.size.y;
let distance_from_top_border = distance_in_pixels - half_thickness;
let distance_from_bottom_border = distance_in_pixels + half_thickness;
let alpha = saturate(0.5 - max(-distance_from_bottom_border, distance_from_top_border));
return input.color * vec4<f32>(1.0, 1.0, 1.0, alpha);
}
// --- monochrome sprites --- //
struct MonochromeSprite {
view_id: ViewId,
layer_id: u32,
order: u32,
bounds: Bounds,
content_mask: Bounds,
color: Hsla,
tile: AtlasTile,
}
var<storage, read> b_mono_sprites: array<MonochromeSprite>;
struct MonoSpriteVarying {
@builtin(position) position: vec4<f32>,
@location(0) tile_position: vec2<f32>,
@location(1) @interpolate(flat) color: vec4<f32>,
@location(3) clip_distances: vec4<f32>,
}
@vertex
fn vs_mono_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> MonoSpriteVarying {
let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
let sprite = b_mono_sprites[instance_id];
var out = MonoSpriteVarying();
out.position = to_device_position(unit_vertex, sprite.bounds);
out.tile_position = to_tile_position(unit_vertex, sprite.tile);
out.color = hsla_to_rgba(sprite.color);
out.clip_distances = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.content_mask);
return out;
}
@fragment
fn fs_mono_sprite(input: MonoSpriteVarying) -> @location(0) vec4<f32> {
let sample = textureSample(t_sprite, s_sprite, input.tile_position).r;
// Alpha clip after using the derivatives.
if (any(input.clip_distances < vec4<f32>(0.0))) {
return vec4<f32>(0.0);
}
return input.color * vec4<f32>(1.0, 1.0, 1.0, sample);
}
// --- polychrome sprites --- //
struct PolychromeSprite {
view_id: ViewId,
layer_id: u32,
order: u32,
bounds: Bounds,
content_mask: Bounds,
corner_radii: Corners,
tile: AtlasTile,
grayscale: u32,
pad: u32,
}
var<storage, read> b_poly_sprites: array<PolychromeSprite>;
struct PolySpriteVarying {
@builtin(position) position: vec4<f32>,
@location(0) tile_position: vec2<f32>,
@location(1) @interpolate(flat) sprite_id: u32,
@location(3) clip_distances: vec4<f32>,
}
@vertex
fn vs_poly_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PolySpriteVarying {
let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
let sprite = b_poly_sprites[instance_id];
var out = PolySpriteVarying();
out.position = to_device_position(unit_vertex, sprite.bounds);
out.tile_position = to_tile_position(unit_vertex, sprite.tile);
out.sprite_id = instance_id;
out.clip_distances = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.content_mask);
return out;
}
@fragment
fn fs_poly_sprite(input: PolySpriteVarying) -> @location(0) vec4<f32> {
let sample = textureSample(t_sprite, s_sprite, input.tile_position);
// Alpha clip after using the derivatives.
if (any(input.clip_distances < vec4<f32>(0.0))) {
return vec4<f32>(0.0);
}
let sprite = b_poly_sprites[input.sprite_id];
let distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii);
var color = sample;
if ((sprite.grayscale & 0xFFu) != 0u) {
let grayscale = dot(color.rgb, GRAYSCALE_FACTORS);
color = vec4<f32>(vec3<f32>(grayscale), sample.a);
}
color.a *= saturate(0.5 - distance);
return color;;
}
// --- surface sprites --- //
@@ -13,12 +13,12 @@ use raw_window_handle::{
use wayland_client::{protocol::wl_surface, Proxy};
use wayland_protocols::xdg::shell::client::xdg_toplevel;
use crate::platform::linux::blade_renderer::BladeRenderer;
use crate::platform::blade::BladeRenderer;
use crate::platform::linux::wayland::display::WaylandDisplay;
use crate::platform::{PlatformAtlas, PlatformInputHandler, PlatformWindow};
use crate::scene::Scene;
use crate::{
px, Bounds, Modifiers, Pixels, PlatformDisplay, PlatformInput, Point, PromptLevel, Size,
px, size, Bounds, Modifiers, Pixels, PlatformDisplay, PlatformInput, Point, PromptLevel, Size,
WindowAppearance, WindowBounds, WindowOptions,
};
@@ -150,11 +150,9 @@ impl WaylandWindowState {
let mut inner = self.inner.lock();
inner.bounds.size.width = width;
inner.bounds.size.height = height;
inner.renderer.resize(gpu::Extent {
width: width as u32,
height: height as u32,
depth: 1,
});
inner
.renderer
.update_drawable_size(size(width as f64, height as f64));
}
let mut callbacks = self.callbacks.lock();
if let Some(ref mut fun) = callbacks.resize {
@@ -341,7 +339,7 @@ impl PlatformWindow for WaylandWindow {
fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
let inner = self.0.inner.lock();
inner.renderer.atlas().clone()
inner.renderer.sprite_atlas().clone()
}
fn set_graphics_profiler_enabled(&self, enabled: bool) {
+20 -13
View File
@@ -1,6 +1,20 @@
//todo!(linux): remove
#![allow(unused)]
use crate::{
platform::blade::BladeRenderer, size, Bounds, GlobalPixels, Pixels, PlatformDisplay,
PlatformInput, PlatformInputHandler, PlatformWindow, Point, Size, WindowAppearance,
WindowBounds, WindowOptions, X11Display,
};
use blade_graphics as gpu;
use parking_lot::Mutex;
use raw_window_handle as rwh;
use xcb::{
x::{self, StackMode},
Xid as _,
};
use std::{
ffi::c_void,
mem,
@@ -10,17 +24,6 @@ use std::{
sync::{self, Arc},
};
use blade_graphics as gpu;
use parking_lot::Mutex;
use raw_window_handle as rwh;
use xcb::{x, Xid as _};
use crate::platform::linux::blade_renderer::BladeRenderer;
use crate::{
Bounds, GlobalPixels, Pixels, PlatformDisplay, PlatformInput, PlatformInputHandler,
PlatformWindow, Point, Size, WindowAppearance, WindowBounds, WindowOptions, X11Display,
};
#[derive(Default)]
struct Callbacks {
request_frame: Option<Box<dyn FnMut()>>,
@@ -293,9 +296,13 @@ impl X11WindowState {
let mut inner = self.inner.lock();
let old_bounds = mem::replace(&mut inner.bounds, bounds);
do_move = old_bounds.origin != bounds.origin;
//todo!(linux): use normal GPUI types here, refactor out the double
// viewport check and extra casts ( )
let gpu_size = query_render_extent(&self.xcb_connection, self.x_window);
if inner.renderer.viewport_size() != gpu_size {
inner.renderer.resize(gpu_size);
inner
.renderer
.update_drawable_size(size(gpu_size.width as f64, gpu_size.height as f64));
resize_args = Some((inner.content_size(), inner.scale_factor));
}
}
@@ -493,7 +500,7 @@ impl PlatformWindow for X11Window {
fn sprite_atlas(&self) -> sync::Arc<dyn crate::PlatformAtlas> {
let inner = self.0.inner.lock();
inner.renderer.atlas().clone()
inner.renderer.sprite_atlas().clone()
}
fn set_graphics_profiler_enabled(&self, enabled: bool) {