fyrox_graphics/
server.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21#![warn(missing_docs)]
22
23//! Graphics server is an abstraction layer over various graphics APIs used on different platforms
24//! supported by the engine.
25
26use crate::{
27    buffer::{GpuBuffer, GpuBufferDescriptor},
28    error::FrameworkError,
29    framebuffer::{Attachment, GpuFrameBuffer},
30    geometry_buffer::{GpuGeometryBuffer, GpuGeometryBufferDescriptor},
31    gpu_program::{GpuProgram, GpuShader, ShaderKind, ShaderResourceDefinition},
32    gpu_texture::{GpuTexture, GpuTextureDescriptor, GpuTextureKind, PixelKind},
33    query::GpuQuery,
34    read_buffer::GpuAsyncReadBuffer,
35    sampler::{GpuSampler, GpuSamplerDescriptor},
36    stats::PipelineStatistics,
37    PolygonFace, PolygonFillMode,
38};
39use fyrox_core::define_as_any_trait;
40use std::fmt::{Display, Formatter};
41use std::rc::{Rc, Weak};
42
43/// Graphics server capabilities.
44#[derive(Debug)]
45pub struct ServerCapabilities {
46    /// The maximum size in basic machine units of a uniform block, which must be at least 16384.
47    pub max_uniform_block_size: usize,
48    /// The minimum required alignment for uniform buffer sizes and offset. The initial value is 1.
49    pub uniform_buffer_offset_alignment: usize,
50    /// The maximum, absolute value of the texture level-of-detail bias. The value must be at least
51    /// 2.0.
52    pub max_lod_bias: f32,
53}
54
55/// Contains information about used memory per each category of GPU resource. This is not precise
56/// data; it only calculates total requested memory by the user of a graphics server and does not
57/// include additional memory overhead in the video driver. Yet this information could still be
58/// useful.
59#[derive(Default, Debug, Clone)]
60pub struct ServerMemoryUsage {
61    /// Total number of bytes used by all textures (including render targets).
62    pub textures: usize,
63    /// Total number of bytes used by all buffers (vertex, index, uniform, etc.)
64    pub buffers: usize,
65}
66
67impl Display for ServerMemoryUsage {
68    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
69        const MEGABYTE: f32 = 1024.0 * 1024.0;
70        write!(
71            f,
72            "Textures: {:.3} Mb\nBuffers: {:.3} Mb",
73            self.textures as f32 / MEGABYTE,
74            self.buffers as f32 / MEGABYTE
75        )
76    }
77}
78
79/// A shared reference to a graphics server.
80pub type SharedGraphicsServer = Rc<dyn GraphicsServer>;
81
82define_as_any_trait!(GraphicsServerAsAny => GraphicsServer);
83
84/// Graphics server is an abstraction layer over various graphics APIs used on different platforms
85/// supported by the engine. Such abstraction layer tries to provide more or less high-level and
86/// unified interface, that can be used to build graphics pipelines quickly and more or less efficiently.
87///
88/// Low-level GAPI-specific optimizations could be performed using direct access to the underlying API,
89/// by downcasting to a specific type.
90pub trait GraphicsServer: GraphicsServerAsAny {
91    /// Creates a GPU buffer with the given size and kind. Usage is a hint to the video driver
92    /// that allows to perform some potential performance optimizations.
93    fn create_buffer(&self, desc: GpuBufferDescriptor) -> Result<GpuBuffer, FrameworkError>;
94
95    /// Creates a new GPU texture using the given descriptor.
96    fn create_texture(&self, desc: GpuTextureDescriptor) -> Result<GpuTexture, FrameworkError>;
97
98    /// Creates a new GPU sampler that can be used to sample texels from a texture.
99    fn create_sampler(&self, desc: GpuSamplerDescriptor) -> Result<GpuSampler, FrameworkError>;
100
101    /// Creates a new frame buffer using the given depth and color attachments. Depth attachment
102    /// not exist, but there must be at least one color attachment of a format that supports rendering.
103    fn create_frame_buffer(
104        &self,
105        depth_attachment: Option<Attachment>,
106        color_attachments: Vec<Attachment>,
107    ) -> Result<GpuFrameBuffer, FrameworkError>;
108
109    /// Creates a frame buffer that "connected" to the final image that will be displayed to the
110    /// screen.
111    fn back_buffer(&self) -> GpuFrameBuffer;
112
113    /// Creates a new GPU query, that can perform asynchronous data fetching from GPU. Usually it
114    /// is used to create occlusion queries.
115    fn create_query(&self) -> Result<GpuQuery, FrameworkError>;
116
117    /// Creates a new named GPU shader. The name could be used for debugging purposes. The
118    /// implementation of graphics server will generate proper resource bindings in the shader code
119    /// for you.
120    fn create_shader(
121        &self,
122        name: String,
123        kind: ShaderKind,
124        source: String,
125        resources: &[ShaderResourceDefinition],
126        line_offset: isize,
127    ) -> Result<GpuShader, FrameworkError>;
128
129    /// Creates a new named GPU program using source code of both vertex and fragment shaders. The
130    /// name could be used for debugging purposes. The implementation of graphics server will generate
131    /// proper resource bindings in the shader code for you.
132    fn create_program(
133        &self,
134        name: &str,
135        vertex_source: String,
136        vertex_source_line_offset: isize,
137        fragment_source: String,
138        fragment_source_line_offset: isize,
139        resources: &[ShaderResourceDefinition],
140    ) -> Result<GpuProgram, FrameworkError>;
141
142    /// Creates a new named GPU program using a pair of vertex and fragment shaders. The name could
143    /// be used for debugging purposes. The implementation of graphics server will generate proper
144    /// resource bindings in the shader code for you.
145    fn create_program_from_shaders(
146        &self,
147        name: &str,
148        vertex_shader: &GpuShader,
149        fragment_shader: &GpuShader,
150        resources: &[ShaderResourceDefinition],
151    ) -> Result<GpuProgram, FrameworkError>;
152
153    /// Creates a new read-back buffer, that can be used to obtain texture data from GPU. It can be
154    /// used to read rendering result from GPU to CPU memory and save the result to disk.
155    fn create_async_read_buffer(
156        &self,
157        name: &str,
158        pixel_size: usize,
159        pixel_count: usize,
160    ) -> Result<GpuAsyncReadBuffer, FrameworkError>;
161
162    /// Creates a new geometry buffer, which consists of one or more vertex buffers and only one
163    /// element buffer. Geometry buffer could be considered as a complex mesh storage allocated on
164    /// GPU.
165    fn create_geometry_buffer(
166        &self,
167        desc: GpuGeometryBufferDescriptor,
168    ) -> Result<GpuGeometryBuffer, FrameworkError>;
169
170    /// Creates a weak reference to the shared graphics server.
171    fn weak(self: Rc<Self>) -> Weak<dyn GraphicsServer>;
172
173    /// Sends all scheduled GPU command buffers for execution on GPU without waiting for a certain
174    /// threshold.
175    fn flush(&self);
176
177    /// Waits until all the scheduled GPU commands are fully executed. This is blocking operation, and
178    /// it blocks the current thread until all the commands are fully executed.
179    fn finish(&self);
180
181    /// Unbinds the all bound resources from the graphics pipeline.
182    fn invalidate_resource_bindings_cache(&self);
183
184    /// Returns GPU pipeline statistics. See [`PipelineStatistics`] for more info.
185    fn pipeline_statistics(&self) -> PipelineStatistics;
186
187    /// Swaps the front and back buffers and thus presenting the final image on screen. There could
188    /// be more than two buffers, and it is up to the graphics server implementation to choose the
189    /// right amount, but it can't be less than two.
190    fn swap_buffers(&self) -> Result<(), FrameworkError>;
191
192    /// Notifies the graphics server that the size of the back buffer has changed. It has very limited
193    /// use and there are very few platforms (Linux with Wayland mostly) that needs this function to
194    /// be called.
195    fn set_frame_size(&self, new_size: (u32, u32));
196
197    /// Returns current capabilities of the graphics server. See [`ServerCapabilities`] for more info.
198    fn capabilities(&self) -> ServerCapabilities;
199
200    /// Sets current polygon fill mode for front faces, back faces, or both.
201    /// The mode of front faces is controlled separately from the mode of back faces,
202    /// and `polygon_face` determines which mode is set by this method.
203    /// See [`PolygonFace`] and [`PolygonFillMode`] docs for more info.
204    fn set_polygon_fill_mode(&self, polygon_face: PolygonFace, polygon_fill_mode: PolygonFillMode);
205
206    /// Generates mipmaps for the given texture. Graphics server implementation can pick any desired
207    /// way of mipmaps generation, depending on the underlying GAPI capabilities.
208    fn generate_mipmap(&self, texture: &GpuTexture);
209
210    /// Fetches the total amount of memory used by the graphics server.
211    fn memory_usage(&self) -> ServerMemoryUsage;
212
213    /// A shortcut for [`Self::create_texture`], that creates a rectangular texture with the given
214    /// size and pixel kind.
215    fn create_2d_render_target(
216        &self,
217        name: &str,
218        pixel_kind: PixelKind,
219        width: usize,
220        height: usize,
221    ) -> Result<GpuTexture, FrameworkError> {
222        self.create_texture(GpuTextureDescriptor {
223            name,
224            kind: GpuTextureKind::Rectangle { width, height },
225            pixel_kind,
226            ..Default::default()
227        })
228    }
229
230    /// A shortcut for [`Self::create_texture`], that creates a cube texture with the given
231    /// size and pixel kind.
232    fn create_cube_render_target(
233        &self,
234        name: &str,
235        pixel_kind: PixelKind,
236        size: usize,
237    ) -> Result<GpuTexture, FrameworkError> {
238        self.create_texture(GpuTextureDescriptor {
239            name,
240            kind: GpuTextureKind::Cube { size },
241            pixel_kind,
242            ..Default::default()
243        })
244    }
245}