pub struct Graphics {
pub camera: Camera2D,
pub camera3d: Camera3D,
/* private fields */
}Fields§
§camera: Camera2D§camera3d: Camera3DPerspective camera for 3D meshes. Set its fields to move the view.
Implementations§
Source§impl Graphics
impl Graphics
Sourcepub async fn new(
window: Arc<Window>,
config: &GraphicsConfig,
) -> Result<Graphics, Error>
pub async fn new( window: Arc<Window>, config: &GraphicsConfig, ) -> Result<Graphics, Error>
Create the surface and device for window. Fails with a
DeviceRequirementsError when the adapter lacks a
limit or feature from config.
pub fn resize(&mut self, width: u32, height: u32)
Sourcepub fn set_virtual_resolution(&mut self, resolution: Option<(u32, u32)>)
pub fn set_virtual_resolution(&mut self, resolution: Option<(u32, u32)>)
Draw into a fixed-size canvas of (width, height) pixels that is scaled onto the
window, or (None) straight into the window again. Usually set once through
AppConfig::virtual_resolution; changing it at runtime reallocates the canvas.
See GraphicsConfig::virtual_resolution.
The toolkit’s input follows right after the update that changed it: the next
update step and render already read mouse_pos and touches in the new canvas
pixels. With ScaleMode::Integer, a canvas larger than the window is scaled down to
fit (fractionally) rather than cropped; use Self::set_scale_mode for per-resolution
choices, e.g. Fit for 800 x 600 on a 1080p screen.
Sourcepub fn virtual_resolution(&self) -> Option<(u32, u32)>
pub fn virtual_resolution(&self) -> Option<(u32, u32)>
The virtual resolution set by Self::set_virtual_resolution, if any.
Sourcepub fn add_post_effect(
&mut self,
stage: PostStage,
effect: impl PostEffect,
) -> PostEffectId
pub fn add_post_effect( &mut self, stage: PostStage, effect: impl PostEffect, ) -> PostEffectId
Run effect on every frame from now on, after the effects already in stage. See
PostStage for the two stages and ShaderEffect for
single-shader effects. While any effect is registered, the scene is drawn into an
offscreen texture (window-sized without a virtual resolution).
Sourcepub fn is_indexed(&self) -> bool
pub fn is_indexed(&self) -> bool
Whether the canvas holds palette indices (feature indexed); always false without it.
Sourcepub fn remove_post_effect(&mut self, id: PostEffectId) -> bool
pub fn remove_post_effect(&mut self, id: PostEffectId) -> bool
Remove an effect; returns whether it existed.
Sourcepub fn set_post_effect_enabled(&mut self, id: PostEffectId, enabled: bool)
pub fn set_post_effect_enabled(&mut self, id: PostEffectId, enabled: bool)
Switch an effect off (skipped, keeps its place) or back on. Unknown ids are ignored.
Sourcepub fn post_effect_enabled(&self, id: PostEffectId) -> Option<bool>
pub fn post_effect_enabled(&self, id: PostEffectId) -> Option<bool>
Whether an effect is enabled; None for an unknown id.
Sourcepub fn post_effect_mut<T>(&mut self, id: PostEffectId) -> Option<&mut T>where
T: PostEffect,
pub fn post_effect_mut<T>(&mut self, id: PostEffectId) -> Option<&mut T>where
T: PostEffect,
The effect behind id as its concrete type, to change its settings, e.g.
gfx.post_effect_mut::<ShaderEffect>(id).unwrap().set_params(&p). None for an
unknown id or another type.
Sourcepub fn set_scale_mode(&mut self, mode: ScaleMode)
pub fn set_scale_mode(&mut self, mode: ScaleMode)
How the canvas is scaled onto the window. Takes effect on the next frame.
pub fn scale_mode(&self) -> ScaleMode
Sourcepub fn set_scale_filter(&mut self, filter: ScaleFilter)
pub fn set_scale_filter(&mut self, filter: ScaleFilter)
Nearest (crisp, default) or linear filtering when scaling the canvas.
pub fn scale_filter(&self) -> ScaleFilter
Sourcepub fn set_border_color(&mut self, color: impl Into<Color>)
pub fn set_border_color(&mut self, color: impl Into<Color>)
Colour of the window area around the canvas (letterbox / pillarbox bars).
pub fn border_color(&self) -> Color
Sourcepub fn canvas_rect(&self) -> Option<CanvasRect>
pub fn canvas_rect(&self) -> Option<CanvasRect>
Where the canvas lands in the window, in physical pixels, or None without a virtual
resolution. Use CanvasRect::window_to_canvas to map window positions; the toolkit’s
Input already reports the mouse and touches in canvas pixels.
Sourcepub fn canvas_view(&self) -> Option<&TextureView>
pub fn canvas_view(&self) -> Option<&TextureView>
The offscreen texture the painter draws into, when there is one (a virtual resolution
is set, post effects are registered or indexed colour is on), for games that record
their own passes into it (in Self::surface_format, at Self::size). Draw after
the painter has flushed (it clears the canvas) and before Self::flush_pending or
the end of the frame, which scale it onto the window. To draw under painter content,
use Painter::custom instead.
With indexed colour on (Self::is_indexed) it holds palette indices, not colours:
write them with index_out from INDEX_WGSL (feature indexed). An RGBA pass would
write meaningless indices; run colour effects as a PostEffect instead, which sees
the resolved colours.
pub fn window(&self) -> &Arc<Window> ⓘ
Sourcepub fn size(&self) -> (u32, u32)
pub fn size(&self) -> (u32, u32)
The size the painter draws at, in pixels: the virtual resolution when one is set, else the window’s size. Lay out the game with this.
Sourcepub fn window_size(&self) -> (u32, u32)
pub fn window_size(&self) -> (u32, u32)
The window’s (surface’s) size in physical pixels, whether or not a virtual resolution is set. Overlays drawn onto the window itself (egui) use this.
Sourcepub fn surface_format(&self) -> TextureFormat
pub fn surface_format(&self) -> TextureFormat
The color format the frame is rendered in: always an sRGB format, possibly a view of a
non-sRGB surface. Build render pipelines that draw into a Frame with this.
Sourcepub fn multisample(&self) -> MultisampleState
pub fn multisample(&self) -> MultisampleState
Multisample state matching the painter’s render target (AppConfig::msaa_samples),
for pipelines that draw in a Painter::custom pass.
Sourcepub fn depth_stencil(&self) -> Option<DepthStencilState>
pub fn depth_stencil(&self) -> Option<DepthStencilState>
Depth-stencil state matching the painter’s render target, for pipelines that draw in
a Painter::custom pass: None without a depth buffer, else
one that neither tests nor writes depth.
pub fn device(&self) -> &Device
pub fn queue(&self) -> &Queue
Sourcepub fn adapter_info(&self) -> &AdapterInfo
pub fn adapter_info(&self) -> &AdapterInfo
The GPU adapter the device was created on: its name, vendor and backend.
Sourcepub fn backend(&self) -> Backend
pub fn backend(&self) -> Backend
The graphics backend in use, e.g. Vulkan, Metal, BrowserWebGpu or Gl
(WebGL2 on the web).
Sourcepub fn supports_compute(&self) -> bool
pub fn supports_compute(&self) -> bool
Whether compute shaders are available. false on WebGL2, the web fallback when the
browser has no WebGPU; check this in Game::init to show a “WebGPU required” message
instead of failing. The device’s limits and features are on Self::device.
Sourcepub fn unmet_requirements(&self) -> Option<&DeviceRequirementsError>
pub fn unmet_requirements(&self) -> Option<&DeviceRequirementsError>
The required limits and features the device was created without, when
continue_without_requirements is set and the adapter couldn’t provide them; None
when everything was met. Check it in Game::init to show a “this browser/GPU is not
supported” screen through the painter instead of failing to start.
Sourcepub fn load_texture(
&mut self,
path: impl AsRef<Path>,
) -> Result<TextureId, Error>
pub fn load_texture( &mut self, path: impl AsRef<Path>, ) -> Result<TextureId, Error>
Load a PNG from disk and remember its path for Graphics::refresh_textures. Not
available on the web; use Graphics::load_texture_bytes (or ctx.load_texture,
which picks the right one per platform).
Sourcepub fn measure_text(&mut self, s: &str, size_px: f32) -> [f32; 2]
pub fn measure_text(&mut self, s: &str, size_px: f32) -> [f32; 2]
Size [width, height] in pixels that s takes up drawn at size_px (the widest line,
and the height of all lines), for aligning text or sizing a box to fit. Uses the same
layout as drawing, so the result matches Painter::text exactly; measuring and then
drawing the same string shapes it once.
Sourcepub fn builtin_font(&mut self) -> &BitmapFont
pub fn builtin_font(&mut self) -> &BitmapFont
The built-in 5 × 7 pixel font (6 × 8 cells, printable ASCII), uploaded on first use.
Painter::pixel_text draws with it; use this to
measure text.
Sourcepub fn load_font_bytes(&mut self, bytes: Vec<u8>)
pub fn load_font_bytes(&mut self, bytes: Vec<u8>)
Register an extra font face (TTF/OTF bytes) as a glyph fallback for text rendering.
Sourcepub fn load_texture_bytes(
&mut self,
bytes: &[u8],
label: Option<&str>,
) -> Result<TextureId, Error>
pub fn load_texture_bytes( &mut self, bytes: &[u8], label: Option<&str>, ) -> Result<TextureId, Error>
Decode a PNG held in memory and upload it. label names the texture in GPU debuggers
and error messages.
Sourcepub fn refresh_textures<I, P>(&mut self, changed_paths: I) -> usize
pub fn refresh_textures<I, P>(&mut self, changed_paths: I) -> usize
Re-decode any texture whose backing file is in changed_paths and update its bind
group in place. Returns the number of textures actually reloaded.
pub fn create_texture_rgba( &mut self, width: u32, height: u32, rgba: &[u8], label: Option<&str>, ) -> TextureId
Sourcepub fn update_texture_rgba(&mut self, id: TextureId, rgba: &[u8])
pub fn update_texture_rgba(&mut self, id: TextureId, rgba: &[u8])
Overwrite the pixels of an existing texture without reallocating it, for content that
changes every frame (a software-rendered framebuffer, a video frame). rgba must hold
width * height * 4 bytes for the texture’s size; create the texture once with
Self::create_texture_rgba. Unknown ids and size mismatches are logged and ignored.
Sourcepub fn register_texture(
&mut self,
texture: Texture,
view: TextureView,
label: Option<&str>,
) -> TextureId
pub fn register_texture( &mut self, texture: Texture, view: TextureView, label: Option<&str>, ) -> TextureId
Make a texture the game created itself drawable like any other TextureId: the
output of a compute shader, a render target, a video frame decoded on the GPU. The
registry takes ownership of texture and samples it through view (nearest filtering,
TextureWrap::Clamp until changed with Self::set_texture_wrap).
texture needs wgpu::TextureUsages::TEXTURE_BINDING and view a filterable float
format with a 2D dimension. The sprite shader reads view as linear color, so use an
sRGB view (e.g. Rgba8UnormSrgb) for content authored in sRGB like PNG pixels. To
write such a texture from a compute shader, create it as Rgba8Unorm with
STORAGE_BINDING and view_formats: &[Rgba8UnormSrgb], store through an Rgba8Unorm
view and register an Rgba8UnormSrgb one created with usage: Some(TEXTURE_BINDING) (an sRGB view can’t carry STORAGE_BINDING).
Self::update_texture_rgba only writes textures with COPY_DST and 4 bytes per
texel; others are logged and skipped.
pub fn white_texture(&self) -> TextureId
Sourcepub fn set_texture_wrap(&mut self, id: TextureId, wrap: TextureWrap)
pub fn set_texture_wrap(&mut self, id: TextureId, wrap: TextureWrap)
Choose what id shows for UVs outside 0..1: TextureWrap::Clamp (the default for
every texture) stretches the edge texels, TextureWrap::Repeat and
TextureWrap::MirrorRepeat tile. Set Repeat on a texture to tile it across one
quad (Painter::quad_textured with UVs up to [4.0, 10.0], a sprite with
crate::SpriteInstance::with_uv beyond 1.0) instead of drawing a quad per tile.
Keep atlases on Clamp: their regions sample right up to the edge, and with wrapping
a UV of exactly 1.0 bleeds in the opposite edge. The mode survives hot-reloads.
Unknown ids are ignored.
Sourcepub fn texture_wrap(&self, id: TextureId) -> Option<TextureWrap>
pub fn texture_wrap(&self, id: TextureId) -> Option<TextureWrap>
The TextureWrap mode of id, or None for an unknown id.
Sourcepub fn texture_size(&self, id: TextureId) -> Option<[u32; 2]>
pub fn texture_size(&self, id: TextureId) -> Option<[u32; 2]>
Pixel size [width, height] of a loaded texture, or None for an unknown id. Follows
hot-reloads, so it reports the size of the current contents.
Sourcepub fn create_mesh(
&mut self,
vertices: &[MeshVertex],
indices: &[u16],
) -> MeshId
pub fn create_mesh( &mut self, vertices: &[MeshVertex], indices: &[u16], ) -> MeshId
Upload a static mesh (positions + normals, indexed) and return its handle. Meshes are
drawn depth-tested via Graphics::draw_mesh using the perspective Self::camera3d.
Sourcepub fn draw_mesh(&mut self, mesh: MeshId, instance: MeshInstance)
pub fn draw_mesh(&mut self, mesh: MeshId, instance: MeshInstance)
Queue one instance of mesh for this frame. Meshes render before the 2D layers, so
2D sprites, primitives and text draw on top of them.
Sourcepub fn request_screenshot(&mut self, path: impl Into<PathBuf>)
pub fn request_screenshot(&mut self, path: impl Into<PathBuf>)
Save a PNG of the next presented frame to path. The read-back stalls that frame, so
this is for debug/dev use. A no-op (with a warning) if the surface lacks COPY_SRC,
and on the web, where there is neither a blocking read-back nor a filesystem.
pub fn begin_frame(&mut self) -> Result<Frame, Error>
pub fn present(&mut self, frame: Frame)
Sourcepub fn flush_pending(&mut self, frame: &mut Frame)
pub fn flush_pending(&mut self, frame: &mut Frame)
Flush all queued 2D layers (sprites + shapes + primitives + text) into the current
frame and, with a virtual resolution, scale the canvas onto the window. Call it
before stacking passes that draw onto the window itself (e.g. egui); after it, the
window view holds the finished scene. The end of the frame does the same if needed.
Auto Trait Implementations§
impl !Freeze for Graphics
impl !RefUnwindSafe for Graphics
impl !Send for Graphics
impl !Sync for Graphics
impl !UnwindSafe for Graphics
impl Forget for Graphics
impl Unpin for Graphics
impl UnsafeUnpin for Graphics
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can
then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be
further downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.