Skip to main content

GPU

Struct GPU 

Source
pub struct GPU {
    pub ctx: RenderContext,
    pub poly_mode: PolyMode,
    pub cull_face: Cull,
    pub bg_color: RGBA,
    pub msaa: bool,
    pub msaa_samples: u32,
    pub culling: bool,
    pub fallback_shader2d: Shader,
    pub fallback_shader3d: Shader,
    pub fallback_texture: Texture2D,
    pub canvas_size: Size2D,
    /* private fields */
}
Expand description

The primary renderer — owns the GL context, fallback assets, and global pipeline state.

GPU is the central rendezvous point between CPU and GPU. It owns:

OwnerTypePurpose
GL contextRenderContextEGL/GLX/WGL surface and function pointers
Fallback shadersShaderBuilt-in 2D and 3D shaders (used when no custom shader is provided)
Fallback textureTexture2DCheckerboard texture for untextured meshes
Pipeline configPolygon mode, culling, MSAA, clear colour

§Lifecycle

A GPU is created once at startup and lives for the entire application session. It is not Send — OpenGL contexts are thread-bound on most platforms.

§Creating a GPU

ConstructorUse case
GPU::new_headlessOff-screen / compute-only (no window)
GPU::new_windowedOn-screen rendering

§Fallback assets

On construction, GPU loads built-in default shaders and a checkerboard fallback texture. ship_mesh3d and ship_mesh2d attach these automatically, so you can render something immediately without providing custom shaders.

§Example

use optic_render::GPU;

let gpu = GPU::new_headless()?;
gpu.log_backend_info();
// → "BACKEND: 4.6.0 NVIDIA ... (GLSL 4.60)"

Fields§

§ctx: RenderContext§poly_mode: PolyMode§cull_face: Cull§bg_color: RGBA§msaa: bool§msaa_samples: u32§culling: bool§fallback_shader2d: Shader§fallback_shader3d: Shader§fallback_texture: Texture2D§canvas_size: Size2D

Implementations§

Source§

impl GPU

Source

pub fn new_headless() -> OpticResult<Self>

Creates a headless GPU context (no window).

Useful for:

  • Off-screen rendering (compute FBOs)
  • Automated testing
  • Server-side rendering

The context uses an EGL PBuffer surface (or platform equivalent).

Source

pub fn new_windowed( raw_handle: RawWindowHandle, display_handle: RawDisplayHandle, size: Size2D, ) -> OpticResult<Self>

Creates a GPU context backed by an on-screen window.

raw_handle and display_handle come from the windowing system (e.g. winit). See [optic_window] for how to acquire them.

§Errors

Returns an error if the EGL/GLX surface cannot be created.

Source

pub fn version(&self) -> &str

Returns the OpenGL version string, e.g. "4.6.0 NVIDIA 545.84".

Source

pub fn lang_version(&self) -> &str

Returns the GLSL version string, e.g. "4.60".

Source

pub fn name(&self) -> &str

Returns the GPU device name, e.g. "GeForce RTX 3080".

Source

pub fn log_backend_info(&self)

Logs the OpenGL and GLSL version at the INFO level.

Source

pub fn log_info(&self)

Logs the current pipeline configuration (polygon mode, culling, MSAA) at the INFO level.

Source

pub fn clear(&self)

Clears the current render target using the configured background colour.

Equivalent to clear_target(None, true) — preserves bg_color and clears depth.

Source

pub fn clear_target(&mut self, color: Option<RGBA>, depth: bool)

Clears the currently-bound render target with explicit control.

ParameterSome / trueNone / false
colorSets bg_color and clears colour bufferLeaves colour buffer untouched
depthClears depth bufferLeaves depth buffer untouched
// Clear colour to red, leave depth as-is
gpu.clear_target(Some(RED.into()), false);

// Clear both with current bg_color
gpu.clear_target(None, true);
Source

pub fn set_bg_color(&mut self, color: RGBA)

Sets the background clear colour.

Applied the next time clear or clear_target is called.

Source

pub fn set_poly_mode(&mut self, mode: PolyMode)

Sets the polygon rasterization mode.

ModeEffect
PolyMode::FilledSolid triangles (default)
PolyMode::WireFrameTriangle outlines
PolyMode::PointsVertex points
Source

pub fn toggle_wireframe(&mut self)

Toggles between filled and wireframe mode.

Source

pub fn set_wire_width(&mut self, width: f32)

Sets the line width used in wireframe mode.

Note: glLineWidth is deprecated in core OpenGL and may not work on all drivers. Prefer a geometry shader for thick lines.

Source

pub fn set_point_size(&self, size: f32)

Sets the point size used when PolyMode::Points is active.

Source

pub fn set_msaa(&mut self, enable: bool)

Enables or disables multisample anti-aliasing.

Source

pub fn toggle_msaa(&mut self)

Toggles MSAA on/off.

Source

pub fn set_msaa_samples(&mut self, samples: u32)

Sets the MSAA sample count for newly created canvases.

Existing canvases are not affected. The driver’s maximum sample count is available at GPU::max_samples at runtime.

Source

pub fn set_culling(&mut self, enable: bool)

Enables or disables back-face culling.

Source

pub fn toggle_culling(&mut self)

Toggles back-face culling on/off.

Source

pub fn set_cull_face(&mut self, cull_face: Cull)

Sets which face is culled (clockwise or counter-clockwise).

Vertices in counter-clockwise order (the default in OpenGL) are front-facing. Set to Cull::Clock to cull the front face instead.

Source

pub fn flip_cull_face(&mut self)

Flips the cull face between clockwise and counter-clockwise.

Source

pub fn set_canvas_size(&mut self, size: Size2D)

Sets the logical canvas size (defines the 2D orthographic projection).

This is the size used by render2d to compute its aspect-correct orthographic matrix.

Source

pub fn current_render_target_size(&self) -> Size2D

Returns the size of the currently-bound render target.

Updated whenever set_render_target is called.

Source

pub fn fallback_shader3d(&self) -> Shader

Returns a clone of the 3D fallback shader (with the fallback texture pre-bound).

Useful when you want to render a mesh without writing a custom shader:

let mut mesh = gpu.ship_mesh3d(&my_mesh_file);
mesh.shader = Some(gpu.fallback_shader3d());
Source

pub fn fallback_shader2d(&self) -> Shader

Returns a clone of the 2D fallback shader (with the fallback texture pre-bound).

Source

pub fn ship_mesh3d(&self, file: &Mesh3DFile) -> Mesh3D

Uploads a Mesh3DFile to the GPU and returns a Mesh3D with the fallback 3D shader attached.

The returned mesh is immediately renderable:

let cube = Mesh3DFile::cube(2.0);
let mesh = gpu.ship_mesh3d(&cube);
gpu.render3d(&mesh, &camera);
Source

pub fn ship_mesh2d(&self, file: &Mesh2DFile) -> Mesh2D

Uploads a Mesh2DFile to the GPU and returns a Mesh2D with the fallback 2D shader attached.

Source

pub fn ship_shader(&self, asset: &ShaderFile) -> Option<Shader>

Compiles a ShaderFile into a usable Shader.

Returns None if compilation or linking fails (errors are logged internally by the GLSL compiler). A returned shader is ready to bind uniforms and attach textures.

Source

pub fn ship_texture(&self, image: &TextureFile) -> Texture2D

Uploads a TextureFile to the GPU.

let tex_file = TextureFile::from_disk("assets/grass.png")?;
let tex: Texture2D = gpu.ship_texture(&tex_file);
Source

pub fn ship_gradient(&self, gradient: &Gradient, resolution: u32) -> Texture2D

Bakes a Gradient into a 1-pixel-high 2D texture (colour ramp).

resolution controls the width of the texture (number of samples). Each sample is linearly interpolated from the gradient and stored as RGBA8.

use optic_core::Gradient;

let grad = Gradient::rainbow();
let ramp: Texture2D = gpu.ship_gradient(&grad, 256);
// Use as a lookup texture in a shader
Source

pub fn ship_canvas(&mut self, desc: &CanvasDesc) -> OpticResult<Canvas>

Creates a Canvas (FBO) with hardware capability validation.

Checks the descriptor against the driver’s maximum colour attachments, draw buffers, and MSAA samples before creating the FBO.

§Errors
ConditionError
Too many colour attachments"exceeds GL_MAX_COLOR_ATTACHMENTS"
Too many draw buffers"exceeds GL_MAX_DRAW_BUFFERS"
Too many MSAA samples"exceeds GL_MAX_SAMPLES"
FBO incompleteFramebuffer status error
Source

pub fn set_render_target( &mut self, target: &RenderTarget<'_>, ) -> OpticResult<()>

Binds a render target (screen or canvas) for subsequent draw calls.

Updates the viewport to match the target’s size and records the size in current_target_size.

// Render to a canvas
let canvas = gpu.ship_canvas(&my_desc)?;
gpu.set_render_target(&RenderTarget::Canvas(&canvas))?;
gpu.clear();

// Switch back to screen
gpu.set_render_target(&RenderTarget::Screen)?;
canvas.blit_to_screen(window_size);
Source

pub fn render3d(&self, mesh: &Mesh3D, camera: &Camera)

Draws a 3D mesh through the given camera.

Internally computes MVP = proj × view × model and sends it to the shader before issuing the draw call.

let cube_file = Mesh3DFile::cube(2.0);
let mesh = gpu.ship_mesh3d(&cube_file);

gpu.render3d(&mesh, &camera);
Source

pub fn render2d(&self, mesh: &Mesh2D)

Draws a 2D mesh using an orthographic projection derived from the canvas size.

The projection maps [-aspect, aspect] on X and [-1, 1] on Y where aspect = canvas_width / canvas_height.

let quad_file = Mesh2DFile::quad(&(800, 600).into());
let mesh = gpu.ship_mesh2d(&quad_file);

gpu.render2d(&mesh);

Auto Trait Implementations§

§

impl !Send for GPU

§

impl !Sync for GPU

§

impl Freeze for GPU

§

impl RefUnwindSafe for GPU

§

impl Unpin for GPU

§

impl UnsafeUnpin for GPU

§

impl UnwindSafe for GPU

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<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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>