grafo

Struct Renderer

Source
pub struct Renderer<'a> { /* private fields */ }
Expand description

The renderer for the Grafo library. This is the main struct that is used to render shapes, images, and text.

§Examples

use grafo::{FontFamily, Renderer};
use grafo::Shape;
use grafo::Color;
use grafo::Stroke;
use grafo::{TextAlignment, TextLayout};
use grafo::MathRect;
use wgpu::Surface;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use std::sync::Arc;
use futures::executor::block_on;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;


// Initialize the renderer
let mut renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));

// Add a rectangle shape
let rect = Shape::rect(
    [(100.0, 100.0), (300.0, 200.0)],
    Color::rgb(0, 128, 255), // Blue fill
    Stroke::new(2.0, Color::BLACK), // Black stroke with width 2.0
);
renderer.add_shape(rect, None);

// Add some text
let layout = TextLayout {
    font_size: 24.0,
    line_height: 30.0,
    color: Color::rgb(255, 255, 255), // White text
    area: MathRect {
        min: (50.0, 50.0).into(),
        max: (400.0, 100.0).into(),
    },
    horizontal_alignment: TextAlignment::Center,
    vertical_alignment: TextAlignment::Center,
};
renderer.add_text("Hello, Grafo!", layout, FontFamily::SansSerif , None);

// Render the frame
match renderer.render() {
    Ok(_) => println!("Frame rendered successfully."),
    Err(e) => eprintln!("Rendering error: {:?}", e),
}

// Clear the draw queue after rendering
renderer.clear_draw_queue();

Implementations§

Source§

impl Renderer<'_>

Source

pub async fn new( window: impl Into<SurfaceTarget<'static>>, physical_size: (u32, u32), scale_factor: f64, ) -> Self

Creates a new Renderer instance.

§Parameters
  • window: The surface target (e.g., window) where rendering will occur.
  • physical_size: The physical size of the window in pixels.
  • scale_factor: The scale factor for high-DPI displays.
§Examples
use std::sync::Arc;
use futures::executor::block_on;
use grafo::Renderer;
use wgpu::Surface;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;

// Initialize the renderer
let renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));
Source

pub fn add_shape( &mut self, shape: impl Into<Shape>, clip_to_shape: Option<usize>, ) -> usize

Adds a shape to the draw queue.

§Parameters
  • shape: The shape to be rendered. It can be any type that implements Into<Shape>.
  • clip_to_shape: Optional index of another shape to which this shape should be clipped.
§Returns

The unique identifier (usize) assigned to the added shape.

§Examples
use std::sync::Arc;
use futures::executor::block_on;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use grafo::Renderer;
use grafo::Shape;
use grafo::Color;
use grafo::Stroke;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;

// Initialize the renderer
let mut renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));

let shape_id = renderer.add_shape(
    Shape::rect(
        [(100.0, 100.0), (300.0, 200.0)],
        Color::rgb(0, 128, 255), // Blue fill
        Stroke::new(2.0, Color::BLACK), // Black stroke with width 2.0
    ),
    None,
);
Source

pub fn add_image( &mut self, image: &[u8], physical_image_dimensions: (u32, u32), rect: [(f32, f32); 2], clip_to_shape: Option<usize>, )

Adds an image to the draw queue.

§Parameters
  • image: A byte slice representing the image data.
  • physical_image_dimensions: A tuple representing the image’s width and height in pixels.
  • rect: An array containing two tuples representing the top-left and bottom-right coordinates where the image should be rendered.
  • clip_to_shape: Optional index of a shape to which this image should be clipped.
§Examples
use std::sync::Arc;
use futures::executor::block_on;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use grafo::Renderer;
use grafo::Shape;
use grafo::Color;
use grafo::Stroke;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;

// Initialize the renderer
let mut renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));

let image_data = vec![0; 16]; // A 2x2 black image
renderer.add_image(
    &image_data,
    (2, 2), // Image dimensions
    [(50.0, 50.0), (150.0, 150.0)], // Rendering rectangle
    Some(0), // Clip to shape with ID 0
);
Source

pub fn add_text( &mut self, text: &str, layout: impl Into<TextLayout>, font_family: FontFamily<'_>, clip_to_shape: Option<usize>, )

Adds text to the draw queue. If you want to use a custom font, you need to load it first using the Renderer::load_fonts or Renderer::load_font_from_bytes methods.

§Parameters
  • text: The string of text to be rendered.
  • layout: The layout configuration for the text.
  • font_family: The font family to be used for rendering the text.
  • clip_to_shape: Optional index of a shape to which this text should be clipped.
§Examples
use std::sync::Arc;
use futures::executor::block_on;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use grafo::{FontFamily, MathRect, Renderer, TextAlignment, TextLayout};
use grafo::Shape;
use grafo::Color;
use grafo::Stroke;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;

// Initialize the renderer
let mut renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));

let layout = TextLayout {
    font_size: 24.0,
    line_height: 30.0,
    color: Color::rgb(255, 255, 255), // White text
    area: MathRect {
        min: (50.0, 50.0).into(),
        max: (400.0, 100.0).into(),
    },
    horizontal_alignment: TextAlignment::Center,
    vertical_alignment: TextAlignment::Center,
};
renderer.add_text("Hello, Grafo!", layout, FontFamily::SansSerif, None);
Source

pub fn render(&mut self) -> Result<(), SurfaceError>

Renders all items currently in the draw queue.

This method processes the draw commands for shapes and images, tessellates them, prepares GPU buffers, and executes the rendering pipelines to produce the final frame.

§Errors

Returns a wgpu::SurfaceError if acquiring the next frame fails.

§Examples
use std::sync::Arc;
use futures::executor::block_on;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use grafo::{MathRect, Renderer, TextAlignment, TextLayout};
use grafo::Shape;
use grafo::Color;
use grafo::Stroke;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;

// Initialize the renderer
let mut renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));

// Add shapes, images, and text...

// Render the frame
if let Err(e) = renderer.render() {
    eprintln!("Rendering error: {:?}", e);
}
Source

pub fn clear_draw_queue(&mut self)

Clears all items currently in the draw queue.

This method removes all shapes, images, and text instances from the draw queue, preparing the renderer for the next frame.

§Examples
use std::sync::Arc;
use futures::executor::block_on;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use grafo::{MathRect, Renderer, TextAlignment, TextLayout};
use grafo::Shape;
use grafo::Color;
use grafo::Stroke;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;

// Initialize the renderer
let mut renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));

// Add shapes, images, and text...

// Clear the draw queue
renderer.clear_draw_queue();
Source

pub fn size(&self) -> (u32, u32)

Retrieves the current size of the rendering surface.

§Returns

A tuple (u32, u32) representing the width and height of the window in pixels.

§Examples
use std::sync::Arc;
use futures::executor::block_on;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use grafo::{MathRect, Renderer, TextAlignment, TextLayout};
use grafo::Shape;
use grafo::Color;
use grafo::Stroke;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;

// Initialize the renderer
let mut renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));

let size = renderer.size();
println!("Rendering surface size: {}x{}", size.0, size.1);
Source

pub fn change_scale_factor(&mut self, new_scale_factor: f64)

Changes the scale factor of the renderer (e.g., for DPI scaling).

This method updates the scale factor and resizes the renderer accordingly.

§Parameters
  • new_scale_factor: The new scale factor to apply.
§Examples
use std::sync::Arc;
use futures::executor::block_on;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use grafo::{MathRect, Renderer, TextAlignment, TextLayout};
use grafo::Shape;
use grafo::Color;
use grafo::Stroke;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;

// Initialize the renderer
let mut renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));

// Change the scale factor to 2.0 for high-DPI rendering
renderer.change_scale_factor(2.0);
Source

pub fn resize(&mut self, new_physical_size: (u32, u32))

Resizes the renderer to the specified physical size.

This method updates the renderer’s configuration to match the new window size, reconfigures the surface, and updates all relevant pipelines and bind groups.

§Parameters
  • new_physical_size: A tuple (u32, u32) representing the new width and height in pixels.
§Examples
use std::sync::Arc;
use futures::executor::block_on;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use grafo::{MathRect, Renderer, TextAlignment, TextLayout};
use grafo::Shape;
use grafo::Color;
use grafo::Stroke;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;

// Initialize the renderer
let mut renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));

// Resize the renderer to 1024x768 pixels
renderer.resize((1024, 768));
Source

pub fn load_fonts(&mut self, fonts: impl Iterator<Item = Source>)

Loads fonts from the specified sources.

Loaded fonts can be later used to render text using the Renderer::add_text method.

§Parameters
  • fonts: An iterator of fontdb::Source objects representing the font sources to load.
§Examples
use std::sync::Arc;
use futures::executor::block_on;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use grafo::{MathRect, Renderer, TextAlignment, TextLayout};
use grafo::Shape;
use grafo::Color;
use grafo::Stroke;
use grafo::fontdb;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;

// Initialize the renderer
let mut renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));

let roboto_font_ttf = include_bytes!("../examples/assets/Roboto-Regular.ttf").to_vec();
let roboto_font_source = fontdb::Source::Binary(Arc::new(roboto_font_ttf));
renderer.load_fonts([roboto_font_source].into_iter());
Source

pub fn load_font_from_bytes(&mut self, font_bytes: &[u8])

Loads a font from a byte slice.

Loaded fonts can be later used to render text using the Renderer::add_text method.

§Parameters
  • font_bytes: A slice of bytes representing the font file.
§Examples
use std::sync::Arc;
use futures::executor::block_on;
use winit::event_loop::EventLoop;
use winit::window::WindowBuilder;
use grafo::{MathRect, Renderer, TextAlignment, TextLayout};
use grafo::Shape;
use grafo::Color;
use grafo::Stroke;
use grafo::fontdb;

// This is for demonstration purposes only. If you want a working example with winit, please
// refer to the example in the "examples" folder.
let event_loop = EventLoop::new().expect("To create the event loop");
let window_surface = Arc::new(WindowBuilder::new().build(&event_loop).unwrap());
let physical_size = (800, 600);
let scale_factor = 1.0;

// Initialize the renderer
let mut renderer = block_on(Renderer::new(window_surface, physical_size, scale_factor));

let roboto_font_ttf = include_bytes!("../examples/assets/Roboto-Regular.ttf");
renderer.load_font_from_bytes(roboto_font_ttf);

Auto Trait Implementations§

§

impl<'a> !Freeze for Renderer<'a>

§

impl<'a> !RefUnwindSafe for Renderer<'a>

§

impl<'a> Send for Renderer<'a>

§

impl<'a> Sync for Renderer<'a>

§

impl<'a> Unpin for Renderer<'a>

§

impl<'a> !UnwindSafe for Renderer<'a>

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

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,