Initial commit
This commit is contained in:
commit
6e1613f73f
48 files changed
+13682
No files matched your search
@@ -0,0 +1,171 @@
|
||||
use crate::{color::Srgba, renderer::textures::TextureOptions};
|
||||
use image::{DynamicImage, RgbaImage};
|
||||
use std::{io::Read, num::NonZeroU32, path::Path};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ImageDelta {
|
||||
pub image: ImageData,
|
||||
pub options: TextureOptions,
|
||||
}
|
||||
|
||||
impl ImageDelta {
|
||||
pub fn new<I: Into<ImageData>>(image: I, options: TextureOptions) -> Self {
|
||||
Self {
|
||||
image: image.into(),
|
||||
options,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Order in which data is laid out.
|
||||
/// Doesn't matter for data with a single layer and no mipmaps.
|
||||
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum DataOrder {
|
||||
/// Data is laid out as: `[Layer0Mip0, Layer0Mip1, Layer0Mip2, Layer1Mip0, Layer1Mip1, ...]`
|
||||
/// Used by dds files.
|
||||
#[default]
|
||||
LayerMajor,
|
||||
/// Data is laid out as: `[Layer0Mip0, Layer1Mip0, Layer2Mip0, Layer0Mip1, Layer1Mip1, ...]`
|
||||
/// Used by ktx and ktx2 files.
|
||||
#[allow(dead_code)]
|
||||
MipMajor,
|
||||
}
|
||||
|
||||
impl From<DataOrder> for wgpu::wgt::TextureDataOrder {
|
||||
fn from(value: DataOrder) -> Self {
|
||||
match value {
|
||||
DataOrder::LayerMajor => Self::LayerMajor,
|
||||
DataOrder::MipMajor => Self::MipMajor,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct ImageData {
|
||||
pub format: wgpu::TextureFormat,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub array_layers: u32,
|
||||
pub mipmap_count: NonZeroU32,
|
||||
pub data_order: DataOrder,
|
||||
pub bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl ImageData {
|
||||
pub fn from_solid_color(dimensions: [usize; 2], color: Srgba) -> Self {
|
||||
let width = dimensions[0] as u32;
|
||||
let height = dimensions[1] as u32;
|
||||
Self {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
width,
|
||||
height,
|
||||
array_layers: 1,
|
||||
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
|
||||
data_order: Default::default(),
|
||||
bytes: RgbaImage::from_pixel(width, height, color.0.into()).into_raw(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DynamicImage> for ImageData {
|
||||
fn from(image: DynamicImage) -> Self {
|
||||
Self {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
width: image.width(),
|
||||
height: image.height(),
|
||||
array_layers: 1,
|
||||
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
|
||||
data_order: Default::default(),
|
||||
bytes: image.to_rgba8().into_raw(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RgbaImage> for ImageData {
|
||||
fn from(image: RgbaImage) -> Self {
|
||||
Self {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
width: image.width(),
|
||||
height: image.height(),
|
||||
array_layers: 1,
|
||||
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
|
||||
data_order: Default::default(),
|
||||
bytes: image.into_raw(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ImageData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ImageData")
|
||||
.field("format", &self.format)
|
||||
.field("width", &self.width)
|
||||
.field("height", &self.height)
|
||||
.field("array_layers", &self.array_layers)
|
||||
.field("mipmap_count", &self.mipmap_count)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: clean this up
|
||||
pub fn load_image_file<P: AsRef<Path>>(path: P) -> anyhow::Result<ImageData> {
|
||||
// PoB2 assumes a case insensitive filesystem is used. This can lead to some
|
||||
// files not being found on case sensitive systems.
|
||||
// As a workaround, try using a lower-cased path if the original path doesn't
|
||||
// exist.
|
||||
let path = if path.as_ref().exists() {
|
||||
path.as_ref().to_owned()
|
||||
} else {
|
||||
let mut path = path.as_ref().to_owned();
|
||||
let lowercase_filename = path.file_name().unwrap().to_ascii_lowercase();
|
||||
path.set_file_name(lowercase_filename);
|
||||
path
|
||||
};
|
||||
|
||||
// special handling for compressed dds files
|
||||
if path.extension().and_then(|s| s.to_str()) == Some("zst")
|
||||
&& path
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.map(|s| s.ends_with(".dds"))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
let f = std::fs::File::open(&path)?;
|
||||
let file_len = f.metadata().ok().map(|m| m.len());
|
||||
let mut zstd_decoder = zstd::Decoder::new(f)?;
|
||||
|
||||
let parse_option = dds::header::ParseOptions::new_permissive(file_len);
|
||||
let header = dds::header::Header::read(&mut zstd_decoder, &parse_option)?;
|
||||
let dxgi_format = dds::Format::from_header(&header)?;
|
||||
// zstd_decoder will now be at start of pixel data
|
||||
let non_data_len = dds::header::Header::MAGIC.len() + header.byte_len();
|
||||
let data_len = file_len.and_then(|l| (l as usize).checked_sub(non_data_len));
|
||||
let mut pixel_data = Vec::with_capacity(data_len.unwrap_or(0));
|
||||
zstd_decoder.read_to_end(&mut pixel_data)?;
|
||||
|
||||
let format = match dxgi_format {
|
||||
dds::Format::BC1_UNORM => wgpu::TextureFormat::Bc1RgbaUnorm,
|
||||
dds::Format::BC2_UNORM => wgpu::TextureFormat::Bc2RgbaUnorm,
|
||||
dds::Format::BC3_UNORM => wgpu::TextureFormat::Bc3RgbaUnorm,
|
||||
dds::Format::BC7_UNORM => wgpu::TextureFormat::Bc7RgbaUnorm,
|
||||
dds::Format::R8G8B8A8_UNORM => wgpu::TextureFormat::Rgba8Unorm,
|
||||
_ => anyhow::bail!("Unsupported dxgi format"),
|
||||
};
|
||||
|
||||
let image_data = ImageData {
|
||||
format,
|
||||
width: header.width(),
|
||||
height: header.height(),
|
||||
array_layers: header.array_size(),
|
||||
mipmap_count: header.mipmap_count(),
|
||||
data_order: DataOrder::LayerMajor,
|
||||
bytes: pixel_data,
|
||||
};
|
||||
|
||||
return Ok(image_data);
|
||||
}
|
||||
|
||||
// let image crate deal with other file types
|
||||
let image = image::ImageReader::open(&path)?.decode()?;
|
||||
Ok(image.into())
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Vertex shader bindings
|
||||
struct VertexOutput {
|
||||
@location(0) tex_coord: vec2<f32>,
|
||||
@location(1) color: vec4<f32>, // linear
|
||||
@location(2) layer_idx: u32,
|
||||
@builtin(position) position: vec4<f32>,
|
||||
};
|
||||
|
||||
struct Globals {
|
||||
screen_size: vec2<f32>,
|
||||
};
|
||||
|
||||
@group(0) @binding(0) var<uniform> r_globals: Globals;
|
||||
|
||||
// [u8; 4] as u32 -> [f32; 4]
|
||||
fn unpack_color(color: u32) -> vec4<f32> {
|
||||
return vec4<f32>(
|
||||
f32(color & 255u),
|
||||
f32((color >> 8u) & 255u),
|
||||
f32((color >> 16u) & 255u),
|
||||
f32((color >> 24u) & 255u),
|
||||
) / 255.0;
|
||||
}
|
||||
|
||||
fn position_from_screen(screen_pos: vec2<f32>) -> vec4<f32> {
|
||||
return vec4<f32>(
|
||||
2.0 * screen_pos.x / r_globals.screen_size.x - 1.0,
|
||||
1.0 - 2.0 * screen_pos.y / r_globals.screen_size.y,
|
||||
0.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_main(
|
||||
@location(0) a_pos: vec2<f32>,
|
||||
@location(1) a_tex_coord: vec2<f32>,
|
||||
@location(2) a_color: u32, // non-linear
|
||||
@location(3) a_layer_idx: u32,
|
||||
) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
out.tex_coord = a_tex_coord;
|
||||
out.layer_idx = a_layer_idx;
|
||||
out.color = unpack_color(a_color);
|
||||
out.position = position_from_screen(a_pos);
|
||||
return out;
|
||||
}
|
||||
|
||||
@group(1) @binding(0) var r_tex_color: texture_2d_array<f32>;
|
||||
@group(1) @binding(1) var r_tex_sampler: sampler;
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
// NOTE: PoB incorrectly performs mixing and blending in sRGB space.
|
||||
// To get a similar visual result, we need to do the same.
|
||||
// Vertex colors, texture samples, and the output color are all in sRGB.
|
||||
// Texture formats and output surface formats are selected such that no automatic
|
||||
// conversion between linear <-> sRGB is performed.
|
||||
let tex_color = textureSample(r_tex_color, r_tex_sampler, in.tex_coord, in.layer_idx);
|
||||
var out_color = in.color * tex_color;
|
||||
return out_color;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{
|
||||
LogicalPoint, LogicalQuad, LogicalRect, NormalizedPoint, NormalizedQuad, NormalizedRect,
|
||||
},
|
||||
math::Corners,
|
||||
renderer::textures::TextureId,
|
||||
};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct Vertex {
|
||||
pub pos: LogicalPoint<f32>,
|
||||
pub uv: NormalizedPoint,
|
||||
pub color: Srgba,
|
||||
// TODO: layer_idx is the same for all vertices. use a uniform buffer
|
||||
// and bind it along with the texture. move into Mesh or make part of
|
||||
// TextureId (change into tuple)
|
||||
pub layer_idx: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Mesh {
|
||||
pub vertices: Vec<Vertex>,
|
||||
pub indices: Vec<u32>,
|
||||
pub texture_id: TextureId,
|
||||
}
|
||||
|
||||
impl Mesh {
|
||||
#[inline]
|
||||
pub fn add_rect(
|
||||
&mut self,
|
||||
rect: LogicalRect<f32>,
|
||||
uv: NormalizedRect,
|
||||
color: Srgba,
|
||||
layer_idx: u32,
|
||||
) {
|
||||
let i = self.vertices.len() as u32;
|
||||
self.indices
|
||||
.extend_from_slice(&[i, i + 1, i + 3, i + 1, i + 2, i + 3]);
|
||||
|
||||
self.vertices.extend_from_slice(&[
|
||||
Vertex {
|
||||
pos: rect.top_left(),
|
||||
uv: uv.top_left(),
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: rect.top_right(),
|
||||
uv: uv.top_right(),
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: rect.bottom_right(),
|
||||
uv: uv.bottom_right(),
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: rect.bottom_left(),
|
||||
uv: uv.bottom_left(),
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn add_quad(
|
||||
&mut self,
|
||||
quad: LogicalQuad<f32>,
|
||||
uv: NormalizedQuad,
|
||||
color: Srgba,
|
||||
layer_idx: u32,
|
||||
) {
|
||||
let i = self.vertices.len() as u32;
|
||||
self.indices
|
||||
.extend_from_slice(&[i, i + 1, i + 3, i + 1, i + 2, i + 3]);
|
||||
|
||||
self.vertices.extend_from_slice(&[
|
||||
Vertex {
|
||||
pos: quad.p0,
|
||||
uv: uv.p0,
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: quad.p1,
|
||||
uv: uv.p1,
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: quad.p2,
|
||||
uv: uv.p2,
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: quad.p3,
|
||||
uv: uv.p3,
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.vertices.is_empty() && self.indices.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ClippedMesh {
|
||||
// Only parts of the mesh that intersect with this will be rendered
|
||||
pub clip_rect: LogicalRect<f32>,
|
||||
pub mesh: Mesh,
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/// Generate entire mipmap chain for all layers starting from mip level 0 image data.
|
||||
/// Assumes data to contain one mip level 0 image for each layer in RGBA format.
|
||||
pub fn generate_mipmap_chain(queue: &wgpu::Queue, texture: &wgpu::Texture, data: &[u8]) {
|
||||
assert!(!texture.format().is_compressed());
|
||||
assert!(texture.format().components() == 4);
|
||||
|
||||
let size = texture.size();
|
||||
let block_size = texture.format().block_copy_size(None).unwrap_or(4);
|
||||
let data_size = (size.width * size.height * block_size) as usize;
|
||||
|
||||
let srgb_mapper = fast_image_resize::create_srgb_mapper();
|
||||
|
||||
let mut data_offset = 0;
|
||||
for layer in 0..texture.depth_or_array_layers() {
|
||||
let bytes = data[data_offset..data_size].to_owned();
|
||||
let mut src_image = fast_image_resize::images::Image::from_vec_u8(
|
||||
size.width,
|
||||
size.height,
|
||||
bytes,
|
||||
fast_image_resize::PixelType::U8x4,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
for mip in 1..texture.mip_level_count() {
|
||||
let mut target_size = size.mip_level_size(mip, wgpu::TextureDimension::D2);
|
||||
target_size.depth_or_array_layers = 1; // copying layers separately
|
||||
|
||||
// intermediate buffer that stores linear source image data in a higher
|
||||
// bit depth to avoid loss of information
|
||||
let mut linear_src_image = fast_image_resize::images::Image::new(
|
||||
src_image.width(),
|
||||
src_image.height(),
|
||||
fast_image_resize::PixelType::U16x4,
|
||||
);
|
||||
|
||||
// convert from sRGB space into linear space
|
||||
// resizing needs to be performed in linear space to get the correct visual result
|
||||
srgb_mapper
|
||||
.forward_map(&src_image, &mut linear_src_image)
|
||||
.unwrap();
|
||||
|
||||
let mut dst_image = fast_image_resize::images::Image::new(
|
||||
target_size.width,
|
||||
target_size.height,
|
||||
fast_image_resize::PixelType::U8x4,
|
||||
);
|
||||
|
||||
let mut linear_dst_image = fast_image_resize::images::Image::new(
|
||||
dst_image.width(),
|
||||
dst_image.height(),
|
||||
fast_image_resize::PixelType::U16x4,
|
||||
);
|
||||
|
||||
let mut resizer = fast_image_resize::Resizer::new();
|
||||
resizer
|
||||
.resize(
|
||||
&linear_src_image,
|
||||
&mut linear_dst_image,
|
||||
Some(&fast_image_resize::ResizeOptions {
|
||||
algorithm: fast_image_resize::ResizeAlg::Convolution(
|
||||
fast_image_resize::FilterType::Bilinear,
|
||||
),
|
||||
cropping: fast_image_resize::SrcCropping::None,
|
||||
mul_div_alpha: true,
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// texture needs to be in sRGB, so map back from resized linear image
|
||||
srgb_mapper
|
||||
.backward_map(&linear_dst_image, &mut dst_image)
|
||||
.unwrap();
|
||||
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture,
|
||||
mip_level: mip,
|
||||
origin: wgpu::Origin3d {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: layer,
|
||||
},
|
||||
aspect: wgpu::wgt::TextureAspect::All,
|
||||
},
|
||||
dst_image.buffer(),
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(block_size * target_size.width),
|
||||
rows_per_image: None,
|
||||
},
|
||||
target_size,
|
||||
);
|
||||
|
||||
src_image = dst_image;
|
||||
}
|
||||
|
||||
data_offset += data_size;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{LogicalPoint, LogicalQuad, LogicalRect, LogicalVector, NormalizedQuad, NormalizedRect},
|
||||
fonts::Layout,
|
||||
math::Point,
|
||||
renderer::textures::TextureId,
|
||||
};
|
||||
use ordered_float::OrderedFloat;
|
||||
use std::{
|
||||
hash::{Hash, Hasher},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ClippedPrimitive {
|
||||
pub clip_rect: LogicalRect<f32>,
|
||||
pub primitive: DrawPrimitive,
|
||||
}
|
||||
|
||||
impl Hash for ClippedPrimitive {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
hash_pos(&self.clip_rect.min, state);
|
||||
hash_pos(&self.clip_rect.max, state);
|
||||
self.primitive.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Hash)]
|
||||
pub enum DrawPrimitive {
|
||||
Rect(RectPrimitive),
|
||||
Quad(QuadPrimitive),
|
||||
Text(TextPrimitive),
|
||||
}
|
||||
|
||||
impl DrawPrimitive {
|
||||
pub fn texture_id(&self) -> TextureId {
|
||||
match self {
|
||||
DrawPrimitive::Rect(rect_primitive) => rect_primitive
|
||||
.texture
|
||||
.map_or_else(TextureId::default, |tex| tex.texture_id),
|
||||
DrawPrimitive::Quad(quad_primitive) => quad_primitive
|
||||
.texture
|
||||
.map_or_else(TextureId::default, |tex| tex.texture_id),
|
||||
_ => TextureId::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RectPrimitive {
|
||||
pub rect: LogicalRect<f32>,
|
||||
pub color: Srgba,
|
||||
pub texture: Option<RectTexture>,
|
||||
}
|
||||
|
||||
impl RectPrimitive {
|
||||
pub fn new(rect: LogicalRect<f32>, color: Srgba, texture: Option<RectTexture>) -> Self {
|
||||
Self {
|
||||
rect,
|
||||
color,
|
||||
texture,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn translate(&mut self, direction: LogicalVector<f32>) {
|
||||
self.rect = self.rect.translate(direction);
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for RectPrimitive {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
hash_pos(&self.rect.min, state);
|
||||
hash_pos(&self.rect.max, state);
|
||||
self.color.hash(state);
|
||||
self.texture.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RectTexture {
|
||||
pub texture_id: TextureId,
|
||||
pub uv: NormalizedRect,
|
||||
pub layer_idx: u32,
|
||||
}
|
||||
|
||||
impl RectTexture {
|
||||
pub fn new(texture_id: TextureId, uv: NormalizedRect, layer_idx: u32) -> Self {
|
||||
Self {
|
||||
texture_id,
|
||||
uv,
|
||||
layer_idx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for RectTexture {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.texture_id.hash(state);
|
||||
hash_pos(&self.uv.min, state);
|
||||
hash_pos(&self.uv.max, state);
|
||||
self.layer_idx.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct QuadPrimitive {
|
||||
pub quad: LogicalQuad<f32>,
|
||||
pub color: Srgba,
|
||||
pub texture: Option<QuadTexture>,
|
||||
}
|
||||
|
||||
impl QuadPrimitive {
|
||||
pub fn new(quad: LogicalQuad<f32>, color: Srgba, texture: Option<QuadTexture>) -> Self {
|
||||
Self {
|
||||
quad,
|
||||
color,
|
||||
texture,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn translate(&mut self, direction: LogicalVector<f32>) {
|
||||
self.quad = self.quad.translate(direction);
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for QuadPrimitive {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
hash_pos(&self.quad.p0, state);
|
||||
hash_pos(&self.quad.p1, state);
|
||||
hash_pos(&self.quad.p2, state);
|
||||
hash_pos(&self.quad.p3, state);
|
||||
self.color.hash(state);
|
||||
self.texture.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct QuadTexture {
|
||||
pub texture_id: TextureId,
|
||||
pub uv: NormalizedQuad,
|
||||
pub layer_idx: u32,
|
||||
}
|
||||
|
||||
impl QuadTexture {
|
||||
pub fn new(texture_id: TextureId, uv: NormalizedQuad, layer_idx: u32) -> Self {
|
||||
Self {
|
||||
texture_id,
|
||||
uv,
|
||||
layer_idx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for QuadTexture {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.texture_id.hash(state);
|
||||
hash_pos(&self.uv.p0, state);
|
||||
hash_pos(&self.uv.p1, state);
|
||||
hash_pos(&self.uv.p2, state);
|
||||
hash_pos(&self.uv.p3, state);
|
||||
self.layer_idx.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TextPrimitive {
|
||||
pub pos: LogicalPoint<f32>,
|
||||
pub layout: Arc<Layout>,
|
||||
}
|
||||
|
||||
impl TextPrimitive {
|
||||
pub fn new(pos: LogicalPoint<f32>, layout: Arc<Layout>) -> Self {
|
||||
Self { pos, layout }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn translate(&mut self, direction: LogicalVector<f32>) {
|
||||
self.pos += direction;
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for TextPrimitive {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
hash_pos(&self.pos, state);
|
||||
self.layout.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_pos<H: Hasher, U>(pos: &Point<f32, U>, state: &mut H) {
|
||||
OrderedFloat(pos.x).hash(state);
|
||||
OrderedFloat(pos.x).hash(state);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
use crate::{
|
||||
dpi::{Normalize, NormalizedQuad, NormalizedRect, Uv},
|
||||
fonts::FontAtlasSize,
|
||||
renderer::{
|
||||
mesh::{ClippedMesh, Mesh},
|
||||
primitives::{
|
||||
ClippedPrimitive, DrawPrimitive, QuadPrimitive, QuadTexture, RectPrimitive,
|
||||
RectTexture, TextPrimitive,
|
||||
},
|
||||
textures::TextureId,
|
||||
},
|
||||
};
|
||||
|
||||
/// Converts [`DrawPrimitive`]s into [`Mesh`]es.
|
||||
#[derive(Default)]
|
||||
pub struct Tessellator {
|
||||
last_clipped_meshes_size: usize,
|
||||
}
|
||||
|
||||
impl Tessellator {
|
||||
pub fn convert_clipped_primitives(
|
||||
&mut self,
|
||||
clipped_primitives: impl Iterator<Item = ClippedPrimitive>,
|
||||
font_atlas_size: FontAtlasSize,
|
||||
) -> Vec<ClippedMesh> {
|
||||
profiling::scope!("convert_primitives");
|
||||
|
||||
let mut clipped_meshes = Vec::with_capacity(self.last_clipped_meshes_size);
|
||||
|
||||
for clipped_primitive in clipped_primitives {
|
||||
self.convert_clipped_primitive(clipped_primitive, font_atlas_size, &mut clipped_meshes);
|
||||
}
|
||||
|
||||
self.last_clipped_meshes_size = clipped_meshes.len();
|
||||
clipped_meshes
|
||||
}
|
||||
|
||||
pub fn convert_clipped_primitive(
|
||||
&mut self,
|
||||
clipped_primitive: ClippedPrimitive,
|
||||
font_atlas_size: FontAtlasSize,
|
||||
out_clipped_meshes: &mut Vec<ClippedMesh>,
|
||||
) {
|
||||
let ClippedPrimitive {
|
||||
clip_rect,
|
||||
primitive,
|
||||
} = clipped_primitive;
|
||||
|
||||
if clip_rect.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let start_new_mesh = match out_clipped_meshes.last() {
|
||||
None => true,
|
||||
Some(last_clipped_mesh) => {
|
||||
// append to previous mesh if clip_rect and texture_id match.
|
||||
// otherwise, start a new mesh.
|
||||
!(last_clipped_mesh.clip_rect == clip_rect
|
||||
&& last_clipped_mesh.mesh.texture_id == primitive.texture_id())
|
||||
}
|
||||
};
|
||||
|
||||
if start_new_mesh {
|
||||
out_clipped_meshes.push(ClippedMesh {
|
||||
clip_rect,
|
||||
mesh: Mesh::default(),
|
||||
});
|
||||
}
|
||||
|
||||
let last_clipped_mesh = out_clipped_meshes.last_mut().unwrap();
|
||||
|
||||
match primitive {
|
||||
DrawPrimitive::Rect(rect_primitive) => {
|
||||
self.convert_rect_primitive(rect_primitive, &mut last_clipped_mesh.mesh)
|
||||
}
|
||||
DrawPrimitive::Quad(quad_primitive) => {
|
||||
self.convert_quad_primitive(quad_primitive, &mut last_clipped_mesh.mesh)
|
||||
}
|
||||
DrawPrimitive::Text(text_primitive) => self.convert_text_primitive(
|
||||
text_primitive,
|
||||
font_atlas_size,
|
||||
&mut last_clipped_mesh.mesh,
|
||||
),
|
||||
}
|
||||
|
||||
// This can be empty if a new mesh was started but the conversion from a text primitive
|
||||
// didn't add any vertices. Our renderer doesn't support empty meshes so remove it
|
||||
if last_clipped_mesh.mesh.is_empty() {
|
||||
out_clipped_meshes.pop();
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_rect_primitive(&self, rect_primitive: RectPrimitive, out: &mut Mesh) {
|
||||
let RectPrimitive {
|
||||
rect,
|
||||
color,
|
||||
texture,
|
||||
} = rect_primitive;
|
||||
|
||||
let (texture_id, uv, layer_idx) = match texture {
|
||||
Some(RectTexture {
|
||||
texture_id,
|
||||
uv,
|
||||
layer_idx,
|
||||
}) => (texture_id, uv, layer_idx),
|
||||
None => (TextureId::default(), NormalizedRect::white_uv(), 0),
|
||||
};
|
||||
|
||||
out.add_rect(rect, uv, color, layer_idx);
|
||||
out.texture_id = texture_id;
|
||||
}
|
||||
|
||||
fn convert_quad_primitive(&self, quad_primitive: QuadPrimitive, out: &mut Mesh) {
|
||||
let QuadPrimitive {
|
||||
quad,
|
||||
color,
|
||||
texture,
|
||||
} = quad_primitive;
|
||||
|
||||
let (texture_id, uv, layer_idx) = match texture {
|
||||
Some(QuadTexture {
|
||||
texture_id,
|
||||
uv,
|
||||
layer_idx,
|
||||
}) => (texture_id, uv, layer_idx),
|
||||
None => (TextureId::default(), NormalizedQuad::white_uv(), 0),
|
||||
};
|
||||
|
||||
out.add_quad(quad, uv, color, layer_idx);
|
||||
out.texture_id = texture_id;
|
||||
}
|
||||
|
||||
fn convert_text_primitive(
|
||||
&self,
|
||||
text_primitive: TextPrimitive,
|
||||
font_atlas_size: FontAtlasSize,
|
||||
out: &mut Mesh,
|
||||
) {
|
||||
let TextPrimitive {
|
||||
pos: layout_pos,
|
||||
layout,
|
||||
} = text_primitive;
|
||||
|
||||
if layout.rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
out.vertices.reserve(layout.num_of_vertices);
|
||||
out.indices.reserve(layout.num_of_indices);
|
||||
|
||||
// TODO: align to pixel grid?
|
||||
|
||||
for row in &layout.rows {
|
||||
for glyph in &row.glyphs {
|
||||
let rect = glyph.rect.translate(layout_pos.to_vector());
|
||||
let normalized_uv = glyph.uv.normalize(font_atlas_size);
|
||||
out.add_rect(rect, normalized_uv, glyph.color, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
use std::{
|
||||
collections::hash_map::Entry,
|
||||
path::Path,
|
||||
sync::{Arc, RwLock},
|
||||
};
|
||||
|
||||
use ahash::HashMap;
|
||||
use anyhow::bail;
|
||||
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
renderer::image::{ImageData, ImageDelta, load_image_file},
|
||||
worker_pool::WorkerPool,
|
||||
};
|
||||
|
||||
pub type TextureId = u64;
|
||||
|
||||
pub struct TextureHandle {
|
||||
tex_mngr: Arc<RwLock<TextureManager>>,
|
||||
id: TextureId,
|
||||
}
|
||||
|
||||
impl TextureHandle {
|
||||
pub fn new(tex_mngr: Arc<RwLock<TextureManager>>, id: TextureId) -> Self {
|
||||
Self { tex_mngr, id }
|
||||
}
|
||||
|
||||
pub fn id(&self) -> TextureId {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn size(&self) -> [usize; 2] {
|
||||
self.tex_mngr
|
||||
.read()
|
||||
.unwrap()
|
||||
.get_meta_data(self.id)
|
||||
.map_or([0, 0], |tex| tex.size)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TextureHandle {
|
||||
fn drop(&mut self) {
|
||||
self.tex_mngr.write().unwrap().free(self.id);
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for TextureHandle {
|
||||
fn clone(&self) -> Self {
|
||||
self.tex_mngr.write().unwrap().retain(self.id);
|
||||
Self {
|
||||
tex_mngr: Arc::clone(&self.tex_mngr),
|
||||
id: self.id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct TexturesDelta {
|
||||
pub update: Vec<(TextureId, ImageDelta)>,
|
||||
pub free: Vec<TextureId>,
|
||||
}
|
||||
|
||||
impl TexturesDelta {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.update.is_empty() && self.free.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata about an allocated texture.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TextureMetaData {
|
||||
pub name: String,
|
||||
pub size: [usize; 2],
|
||||
/// Texture is freed when this reaches zero
|
||||
retain_count: usize,
|
||||
pub options: TextureOptions,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct TextureManager {
|
||||
next_id: u64,
|
||||
meta_data: HashMap<TextureId, TextureMetaData>,
|
||||
delta: TexturesDelta,
|
||||
}
|
||||
|
||||
impl TextureManager {
|
||||
/// Allocates a new Texture.
|
||||
pub fn alloc(&mut self, name: String, image: ImageData, options: TextureOptions) -> TextureId {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
|
||||
self.meta_data.entry(id).or_insert_with(|| TextureMetaData {
|
||||
name,
|
||||
size: [image.width as usize, image.height as usize],
|
||||
retain_count: 1,
|
||||
options,
|
||||
});
|
||||
|
||||
self.delta
|
||||
.update
|
||||
.push((id, ImageDelta::new(image, options)));
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Reserves a new TextureId for later assignment.
|
||||
pub fn reserve(&mut self, name: String, options: TextureOptions) -> TextureId {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
|
||||
self.meta_data.entry(id).or_insert_with(|| TextureMetaData {
|
||||
name,
|
||||
size: [0, 0],
|
||||
retain_count: 1,
|
||||
options,
|
||||
});
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Assigns a new image to an existing texture.
|
||||
pub fn set(&mut self, id: TextureId, delta: ImageDelta) {
|
||||
if let Some(meta_data) = self.meta_data.get_mut(&id) {
|
||||
meta_data.size = [delta.image.width as usize, delta.image.height as usize];
|
||||
// discard all old enqueued deltas
|
||||
self.delta.update.retain(|(x, _)| x != &id);
|
||||
self.delta.update.push((id, delta));
|
||||
} else {
|
||||
debug_assert!(false, "Tried setting texture {id:?} which is not allocated");
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees an existing texture.
|
||||
pub fn free(&mut self, id: TextureId) {
|
||||
if let Entry::Occupied(mut entry) = self.meta_data.entry(id) {
|
||||
let meta = entry.get_mut();
|
||||
meta.retain_count -= 1;
|
||||
if meta.retain_count == 0 {
|
||||
entry.remove();
|
||||
self.delta.free.push(id);
|
||||
}
|
||||
} else {
|
||||
debug_assert!(false, "Tried freeing texture {id:?} which is not allocated");
|
||||
}
|
||||
}
|
||||
|
||||
/// Increase the retain-count of the given texture.
|
||||
///
|
||||
/// [`Self::free`] must be called an additional time for each time [`Self::retain`] is called,
|
||||
pub fn retain(&mut self, id: TextureId) {
|
||||
if let Some(meta) = self.meta_data.get_mut(&id) {
|
||||
meta.retain_count += 1;
|
||||
} else {
|
||||
debug_assert!(
|
||||
false,
|
||||
"Tried retaining texture {id:?} which is not allocated",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get metadata about a specific texture.
|
||||
pub fn get_meta_data(&self, id: TextureId) -> Option<&TextureMetaData> {
|
||||
self.meta_data.get(&id)
|
||||
}
|
||||
|
||||
/// Take and reset changes since last frame.
|
||||
pub fn take_delta(&mut self) -> TexturesDelta {
|
||||
std::mem::take(&mut self.delta)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WrappedTextureManager {
|
||||
manager: Arc<RwLock<TextureManager>>,
|
||||
worker_pool: WorkerPool,
|
||||
}
|
||||
|
||||
impl WrappedTextureManager {
|
||||
pub fn new() -> Self {
|
||||
let manager = Arc::new(RwLock::new(TextureManager::default()));
|
||||
|
||||
// allocate default texture (id: 0) for font atlas
|
||||
manager.write().unwrap().alloc(
|
||||
"font_atlas_texture".into(),
|
||||
ImageData::from_solid_color([0, 0], Srgba::TRANSPARENT),
|
||||
TextureOptions::default(),
|
||||
);
|
||||
|
||||
Self {
|
||||
manager,
|
||||
worker_pool: WorkerPool::new(4),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn update_font_texture(&self, delta: ImageDelta) {
|
||||
self.manager
|
||||
.write()
|
||||
.unwrap()
|
||||
.set(TextureId::default(), delta);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn take_delta(&self) -> TexturesDelta {
|
||||
self.manager.write().unwrap().take_delta()
|
||||
}
|
||||
|
||||
pub fn load_texture(
|
||||
&self,
|
||||
image_path: String,
|
||||
options: TextureOptions,
|
||||
is_async: bool,
|
||||
) -> anyhow::Result<TextureHandle> {
|
||||
let manager = Arc::clone(&self.manager);
|
||||
|
||||
let handle = if is_async {
|
||||
let id = manager
|
||||
.write()
|
||||
.unwrap()
|
||||
.reserve(image_path.clone(), options);
|
||||
|
||||
// load image in background worker
|
||||
let mngr_clone = Arc::clone(&manager);
|
||||
self.worker_pool
|
||||
.execute(move || match load_image_file(Path::new(&image_path)) {
|
||||
Ok(image) => {
|
||||
mngr_clone
|
||||
.write()
|
||||
.unwrap()
|
||||
.set(id, ImageDelta::new(image, options));
|
||||
}
|
||||
Err(e) => log::warn!("Unable to load image fron {}: {}", &image_path, e),
|
||||
});
|
||||
|
||||
TextureHandle::new(manager, id)
|
||||
} else {
|
||||
match load_image_file(Path::new(&image_path)) {
|
||||
Ok(image) => {
|
||||
let id = manager.write().unwrap().alloc(image_path, image, options);
|
||||
TextureHandle::new(manager, id)
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("Unable to load image fron {}: {}", &image_path, e);
|
||||
bail!(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
pub fn update_texture(
|
||||
&self,
|
||||
texture_id: TextureId,
|
||||
image_path: String,
|
||||
options: TextureOptions,
|
||||
is_async: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
if is_async {
|
||||
let mngr_clone = Arc::clone(&self.manager);
|
||||
self.worker_pool
|
||||
.execute(move || match load_image_file(Path::new(&image_path)) {
|
||||
Ok(image) => {
|
||||
mngr_clone
|
||||
.write()
|
||||
.unwrap()
|
||||
.set(texture_id, ImageDelta::new(image, options));
|
||||
}
|
||||
Err(e) => log::warn!("Unable to load image fron {}: {}", &image_path, e),
|
||||
});
|
||||
} else {
|
||||
match load_image_file(Path::new(&image_path)) {
|
||||
Ok(image) => {
|
||||
self.manager
|
||||
.write()
|
||||
.unwrap()
|
||||
.set(texture_id, ImageDelta::new(image, options));
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("Unable to load image fron {}: {}", &image_path, e);
|
||||
bail!(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TextureOptions {
|
||||
pub magnification: wgpu::FilterMode,
|
||||
pub minification: wgpu::FilterMode,
|
||||
pub wrap_mode: wgpu::AddressMode,
|
||||
pub mipmap_mode: wgpu::FilterMode,
|
||||
pub generate_mipmaps: bool,
|
||||
}
|
||||
|
||||
impl TextureOptions {
|
||||
pub const LINEAR_REPEAT: Self = Self {
|
||||
magnification: wgpu::FilterMode::Linear,
|
||||
minification: wgpu::FilterMode::Linear,
|
||||
wrap_mode: wgpu::AddressMode::Repeat,
|
||||
mipmap_mode: wgpu::FilterMode::Linear,
|
||||
generate_mipmaps: false,
|
||||
};
|
||||
|
||||
pub const LINEAR: Self = Self {
|
||||
magnification: wgpu::FilterMode::Linear,
|
||||
minification: wgpu::FilterMode::Linear,
|
||||
wrap_mode: wgpu::AddressMode::ClampToEdge,
|
||||
mipmap_mode: wgpu::FilterMode::Linear,
|
||||
generate_mipmaps: false,
|
||||
};
|
||||
}
|
||||
|
||||
impl Default for TextureOptions {
|
||||
fn default() -> Self {
|
||||
Self::LINEAR
|
||||
}
|
||||
}
|
||||
|
||||
impl std::hash::Hash for TextureOptions {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.magnification.hash(state);
|
||||
self.minification.hash(state);
|
||||
self.wrap_mode.hash(state);
|
||||
self.mipmap_mode.hash(state);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user