Skip to main content

pebble/graphics/pipeline/
texture_view.rs

1use crate::graphics::{pipeline::textures::check_texture_dimensions, render::Backend, types::{TextureFormat, flags::TextureUsages}};
2
3/// A GPU texture view — what a [`ColorTarget`](crate::graphics::render::targets::ColorTarget)/
4/// [`DepthTarget`](crate::graphics::render::targets::DepthTarget) or a bind group entry actually
5/// points at. Build one via a texture's `get_view()`, or [`RenderTargetTextureBuilder`] for a
6/// standalone render target.
7pub struct TextureView {
8    view: wgpu::TextureView,
9    _texture: wgpu::Texture,
10}
11
12impl TextureView {
13    pub(crate) fn raw(&self) -> &wgpu::TextureView {
14        &self.view
15    }
16
17    pub(crate) fn from_raw(view: wgpu::TextureView, texture: wgpu::Texture) -> Self {
18        Self { view, _texture: texture }
19    }
20}
21
22/// Builds a standalone [`TextureView`] for use as a render target — e.g. a
23/// post-processing buffer or shadow map, not backed by any [`Texture`](super::textures::Texture) asset.
24pub struct RenderTargetTextureBuilder<'a> {
25    label: Option<&'a str>,
26    width: u32,
27    height: u32,
28    format: TextureFormat,
29    usage: TextureUsages,
30    mip_level_count: u32,
31    sample_count: u32,
32}
33
34impl<'a> RenderTargetTextureBuilder<'a> {
35    pub fn new(width: u32, height: u32, format: TextureFormat) -> Self {
36        Self {
37            label: None,
38            width,
39            height,
40            format,
41            usage: TextureUsages::empty(),
42            mip_level_count: 1,
43            sample_count: 1,
44        }
45    }
46
47    pub fn with_label(mut self, label: impl Into<Option<&'a str>>) -> Self {
48        self.label = label.into();
49        self
50    }
51
52    pub fn with_usage(mut self, usage: TextureUsages) -> Self {
53        self.usage = usage;
54        self
55    }
56
57    pub fn with_mip_level_count(mut self, count: u32) -> Self {
58        self.mip_level_count = count;
59        self
60    }
61
62    pub fn with_sample_count(mut self, count: u32) -> Self {
63        self.sample_count = count;
64        self
65    }
66
67    pub fn build(self, backend: &Backend) -> TextureView {
68        check_texture_dimensions(&backend.device, "RenderTargetTextureBuilder", self.width, self.height);
69
70        let texture = backend.device.create_texture(&wgpu::TextureDescriptor {
71            label: self.label,
72            size: wgpu::Extent3d { width: self.width, height: self.height, depth_or_array_layers: 1 },
73            mip_level_count: self.mip_level_count,
74            sample_count: self.sample_count,
75            dimension: wgpu::TextureDimension::D2,
76            format: self.format.into(),
77            usage: self.usage.into(),
78            view_formats: &[],
79        });
80        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
81        TextureView { view, _texture: texture }
82    }
83}