Skip to main content

Graphics

Struct Graphics 

Source
pub struct Graphics {
    pub camera: Camera2D,
    pub camera3d: Camera3D,
    /* private fields */
}

Fields§

§camera: Camera2D§camera3d: Camera3D

Perspective camera for 3D meshes. Set its fields to move the view.

Implementations§

Source§

impl Graphics

Source

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.

Source

pub fn resize(&mut self, width: u32, height: u32)

Source

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.

Source

pub fn virtual_resolution(&self) -> Option<(u32, u32)>

The virtual resolution set by Self::set_virtual_resolution, if any.

Source

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).

Source

pub fn is_indexed(&self) -> bool

Whether the canvas holds palette indices (feature indexed); always false without it.

Source

pub fn remove_post_effect(&mut self, id: PostEffectId) -> bool

Remove an effect; returns whether it existed.

Source

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.

Source

pub fn post_effect_enabled(&self, id: PostEffectId) -> Option<bool>

Whether an effect is enabled; None for an unknown id.

Source

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.

Source

pub fn set_scale_mode(&mut self, mode: ScaleMode)

How the canvas is scaled onto the window. Takes effect on the next frame.

Source

pub fn scale_mode(&self) -> ScaleMode

Source

pub fn set_scale_filter(&mut self, filter: ScaleFilter)

Nearest (crisp, default) or linear filtering when scaling the canvas.

Source

pub fn scale_filter(&self) -> ScaleFilter

Source

pub fn set_border_color(&mut self, color: impl Into<Color>)

Colour of the window area around the canvas (letterbox / pillarbox bars).

Source

pub fn border_color(&self) -> Color

Source

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.

Source

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.

Source

pub fn window(&self) -> &Arc<Window> ⓘ

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn device(&self) -> &Device

Source

pub fn queue(&self) -> &Queue

Source

pub fn adapter_info(&self) -> &AdapterInfo

The GPU adapter the device was created on: its name, vendor and backend.

Source

pub fn backend(&self) -> Backend

The graphics backend in use, e.g. Vulkan, Metal, BrowserWebGpu or Gl (WebGL2 on the web).

Source

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.

Source

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.

Source

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).

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn refresh_textures<I, P>(&mut self, changed_paths: I) -> usize
where I: IntoIterator<Item = P>, P: AsRef<Path>,

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.

Source

pub fn create_texture_rgba( &mut self, width: u32, height: u32, rgba: &[u8], label: Option<&str>, ) -> TextureId

Source

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.

Source

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.

Source

pub fn white_texture(&self) -> TextureId

Source

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.

Source

pub fn texture_wrap(&self, id: TextureId) -> Option<TextureWrap>

The TextureWrap mode of id, or None for an unknown id.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn begin_frame(&mut self) -> Result<Frame, Error>

Source

pub fn present(&mut self, frame: Frame)

Source

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§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert 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>

Convert 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)

Convert &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)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more