Struct pix_engine::state::PixState
source · #[non_exhaustive]pub struct PixState { /* private fields */ }
Expand description
Represents all state and methods for updating and interacting with the Engine
.
Implementations§
source§impl PixState
impl PixState
sourcepub fn clear(&mut self) -> PixResult<()>
pub fn clear(&mut self) -> PixResult<()>
Clears the render target to the current background Color set by PixState::background
.
Errors
If the current render target is closed or dropped, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.background(Color::CADET_BLUE);
s.clear();
Ok(())
}
sourcepub fn save_canvas<P, R>(&mut self, src: R, path: P) -> PixResult<()>
pub fn save_canvas<P, R>(&mut self, src: R, path: P) -> PixResult<()>
Save a portion src
of the currently rendered target to a png file. Passing None
for
src
saves the entire target.
Errors
Returns an error for any of the following:
- The current render target is closed or dropped.
- The renderer fails to read pixels from the current window target.
- An io::Error
occurs attempting to create the png file.
- A png::EncodingError
occurs attempting to write image bytes.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
if let Key::S = event.key {
s.save_canvas(None, "test_image.png")?;
}
Ok(false)
}
source§impl PixState
impl PixState
sourcepub fn point<P>(&mut self, p: P) -> PixResult<()>
pub fn point<P>(&mut self, p: P) -> PixResult<()>
Draw a Point to the current canvas. PixState::stroke
controls whether the point is
drawn or not. PixState::stroke_weight
and PixState::fill
have no effect.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.stroke(Color::RED);
s.point(s.mouse_pos())?;
Ok(())
}
sourcepub fn line<L>(&mut self, line: L) -> PixResult<()>
pub fn line<L>(&mut self, line: L) -> PixResult<()>
Draw a Line to the current canvas. PixState::stroke
controls whether the line is drawn
or not. PixState::stroke_weight
controls the line thickness. PixState::fill
has no
effect.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.stroke(Color::RED);
s.line([s.pmouse_pos(), s.mouse_pos()])?;
Ok(())
}
sourcepub fn bezier<P, I>(&mut self, points: I) -> PixResult<()>
pub fn bezier<P, I>(&mut self, points: I) -> PixResult<()>
Draw a cubic Bezier curve to the current canvas. PixState::stroke
controls whether the
line is drawn or not. PixState::bezier_detail
controls the resolution of the
curve. PixState::fill
has no effect.
The first and last points are the anchor points of the curve, while the middle points are the control points that “pull” the curve towards them.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.stroke(Color::RED);
s.bezier([[85, 20], [10, 10], [90, 90], [15, 80]])?;
Ok(())
}
sourcepub fn triangle<T>(&mut self, tri: T) -> PixResult<()>
pub fn triangle<T>(&mut self, tri: T) -> PixResult<()>
Draw a Triangle to the current canvas. PixState::fill
and PixState::stroke
control whether the triangle is filled or outlined.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLACK);
s.stroke(Color::RED);
s.triangle(tri!([10, 0], [-5, 5], [5, 5]))?;
Ok(())
}
sourcepub fn square<R>(&mut self, square: R) -> PixResult<()>
pub fn square<R>(&mut self, square: R) -> PixResult<()>
Draw a square Rect to the current canvas. PixState::fill
and PixState::stroke
control
whether the square is filled or outlined. RectMode
controls how the (x, y)
position is
interpreted.
Alias for PixState::rect
.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLACK);
s.stroke(Color::RED);
s.square(square![s.mouse_pos(), 100])?;
Ok(())
}
sourcepub fn rounded_square<R>(&mut self, square: R, radius: i32) -> PixResult<()>
pub fn rounded_square<R>(&mut self, square: R, radius: i32) -> PixResult<()>
Draw a rounded Square to the current canvas. PixState::fill
and
PixState::stroke
control whether the square is filled or outlined. RectMode
controls
how the (x, y)
position is interpreted.
Alias for PixState::rounded_rect
.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLACK);
s.stroke(Color::RED);
s.rounded_square(square![s.mouse_pos(), 100], 10)?;
Ok(())
}
sourcepub fn rect<R>(&mut self, rect: R) -> PixResult<()>
pub fn rect<R>(&mut self, rect: R) -> PixResult<()>
Draw a Rectangle to the current canvas. PixState::fill
and PixState::stroke
control whether the rect is filled or outlined. RectMode
controls how the (x, y)
position is interpreted.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLACK);
s.stroke(Color::RED);
s.rect(rect![s.mouse_pos(), 100, 100])?;
Ok(())
}
sourcepub fn rounded_rect<R>(&mut self, rect: R, radius: i32) -> PixResult<()>
pub fn rounded_rect<R>(&mut self, rect: R, radius: i32) -> PixResult<()>
Draw a rounded Rectangle to the current canvas. PixState::fill
and
PixState::stroke
control whether the rect is filled or outlined. RectMode
controls how
the (x, y)
position is interpreted.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLACK);
s.stroke(Color::RED);
s.rounded_rect(rect![s.mouse_pos(), 100, 100], 10)?;
Ok(())
}
sourcepub fn quad<Q>(&mut self, quad: Q) -> PixResult<()>
pub fn quad<Q>(&mut self, quad: Q) -> PixResult<()>
Draw a Quadrilateral to the current canvas. PixState::fill
and
PixState::stroke
control whether the quad is filled or outlined. RectMode
has no
effect.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLACK);
s.stroke(Color::RED);
s.quad(quad![10, 20, 30, 10, 20, 25, 15, 15])?;
Ok(())
}
sourcepub fn polygon<P, I>(&mut self, points: I) -> PixResult<()>
pub fn polygon<P, I>(&mut self, points: I) -> PixResult<()>
Draw a polygon to the current canvas. PixState::fill
and PixState::stroke
control
whether the polygon is filled or outlined. RectMode
has no effect.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLACK);
s.stroke(Color::RED);
s.polygon([[10, 10], [50, 20], [70, 30], [60, 50], [10, 50]])?;
Ok(())
}
sourcepub fn wireframe<V, P1, P2, A, S>(
&mut self,
vertexes: V,
pos: P2,
angle: A,
scale: S
) -> PixResult<()>
pub fn wireframe<V, P1, P2, A, S>( &mut self, vertexes: V, pos: P2, angle: A, scale: S ) -> PixResult<()>
Draw a wireframe to the current canvas, translated to a given Point and optionally
rotated by angle
and scaled
. PixState::fill
and PixState::stroke
control whether
the wireframe is filled or outlined. angle
can be in either radians or degrees based on
AngleMode
.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
let wireframe = [
point!(5.0, 0.0),
point!(-2.5, -2.5),
point!(-2.5, 2.5)
];
s.fill(Color::CADET_BLUE);
s.stroke(Color::BLACK);
s.angle_mode(AngleMode::Degrees);
s.wireframe(wireframe, [10, 10], 45.0, 2.0)?;
Ok(())
}
sourcepub fn circle<C>(&mut self, circle: C) -> PixResult<()>
pub fn circle<C>(&mut self, circle: C) -> PixResult<()>
Draw a circle Ellipse to the current canvas. PixState::fill
and PixState::stroke
control whether the circle is filled or outlined. EllipseMode
controls how the (x, y)
position is interpreted.
Alias for PixState::ellipse
.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLACK);
s.stroke(Color::RED);
s.circle(circle![s.mouse_pos(), 100])?;
Ok(())
}
sourcepub fn ellipse<E>(&mut self, ellipse: E) -> PixResult<()>
pub fn ellipse<E>(&mut self, ellipse: E) -> PixResult<()>
Draw a Ellipse to the current canvas. PixState::fill
and PixState::stroke
control
whether the ellipse is filled or outlined. EllipseMode
controls how the (x, y)
position
is interpreted.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLACK);
s.stroke(Color::RED);
s.ellipse(ellipse![s.mouse_pos(), 100, 100])?;
Ok(())
}
sourcepub fn arc<P>(
&mut self,
p: P,
radius: i32,
start: i32,
end: i32
) -> PixResult<()>
pub fn arc<P>( &mut self, p: P, radius: i32, start: i32, end: i32 ) -> PixResult<()>
Draw an arc of a given radius
and length defined by start
and end
to the current
canvas. PixState::fill
and PixState::stroke
control whether the pie is filled or
outlined. ArcMode
changes whether the arc is drawn as an open segment or a pie shape.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLACK);
s.stroke(Color::RED);
s.arc_mode(ArcMode::Pie);
s.arc(s.mouse_pos(), 20, 0, 180)?;
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn enqueue_audio<S: AsRef<[f32]>>(&mut self, samples: S) -> PixResult<()>
pub fn enqueue_audio<S: AsRef<[f32]>>(&mut self, samples: S) -> PixResult<()>
Add samples to the current audio buffer queue.
Errors
If the audio device fails to queue samples, or if the audio buffer max size is reached, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
// Some square wave samples of audio
let volume = 0.2;
let sample_rate = s.audio_sample_rate() as f32;
let sample_count = 4 * sample_rate as usize;
let frequency = 440.0; // A4 note
let mut samples = Vec::with_capacity(sample_count);
for x in 0..sample_count {
let s = (2.0 * PI as f32 * frequency * x as f32 / sample_rate).sin();
samples.push(if s <= 0.0 { -volume } else { volume });
}
// Add samples to audio queue for playback
s.enqueue_audio(&samples)?;
Ok(())
}
sourcepub fn clear_audio(&mut self)
pub fn clear_audio(&mut self)
Clear audio samples from the current audio buffer queue.
sourcepub fn audio_status(&self) -> AudioStatus
pub fn audio_status(&self) -> AudioStatus
Return the status of the current audio queue device.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
match event.key {
Key::Return => {
if s.audio_status() == AudioStatus::Paused {
s.resume_audio();
}
Ok(true)
}
_ => Ok(false),
}
}
sourcepub fn audio_driver(&self) -> &'static str
pub fn audio_driver(&self) -> &'static str
Return the current driver of this audio callback device.
sourcepub fn audio_sample_rate(&self) -> i32
pub fn audio_sample_rate(&self) -> i32
Returns the sample rate for the current audio queue device.
sourcepub fn audio_queued_size(&self) -> u32
pub fn audio_queued_size(&self) -> u32
Returns the queued buffer size of the current audio queue device.
sourcepub fn audio_size(&self) -> u32
pub fn audio_size(&self) -> u32
Returns the buffer size of the current audio queue device.
sourcepub fn resume_audio(&mut self)
pub fn resume_audio(&mut self)
Resumes playback of the current audio queue device.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
match event.key {
Key::Return => {
s.resume_audio();
Ok(true)
}
_ => Ok(false),
}
}
sourcepub fn pause_audio(&mut self)
pub fn pause_audio(&mut self)
Pause playback of the current audio queue device.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
match event.key {
Key::Return => {
s.pause_audio();
Ok(true)
}
_ => Ok(false),
}
}
sourcepub fn open_playback<'a, CB, F, D>(
&self,
device: D,
desired_spec: &AudioSpecDesired,
get_callback: F
) -> PixResult<AudioDevice<CB>>
pub fn open_playback<'a, CB, F, D>( &self, device: D, desired_spec: &AudioSpecDesired, get_callback: F ) -> PixResult<AudioDevice<CB>>
Opens and returns an audio callback device for playback.
The audio device starts out paused
. Call resume to start
playback and pause to stop playback.
Errors
If the renderer fails to open an audio device, then an error is returned.
Example
use pix_engine::prelude::*;
use std::time::Duration;
struct SquareWave {
phase_inc: f32,
phase: f32,
volume: f32,
}
impl AudioCallback for SquareWave {
type Channel = f32;
fn callback(&mut self, out: &mut [Self::Channel]) {
// Generate a square wave
for x in out.iter_mut() {
*x = if self.phase <= 0.5 {
self.volume
} else {
-self.volume
};
self.phase = (self.phase + self.phase_inc) % 1.0;
}
}
}
struct MyApp;
impl PixEngine for MyApp {
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
let desired_spec = AudioSpecDesired {
freq: Some(44_100), // 44,100 HZ
channels: Some(1), // mono audio
samples: None, // default sample size
};
let mut device = s.open_playback(None, &desired_spec, |spec| {
SquareWave {
phase_inc: 440.0 / spec.freq as f32,
phase: 0.0,
volume: 0.25,
}
})?;
// Start playback
device.resume();
// Play for 2 seconds then quit.
std::thread::sleep(Duration::from_millis(2000));
s.quit();
// Device stops playback when dropped.
Ok(())
}
}
sourcepub fn open_capture<'a, CB, F, D>(
&self,
device: D,
desired_spec: &AudioSpecDesired,
get_callback: F
) -> PixResult<AudioDevice<CB>>
pub fn open_capture<'a, CB, F, D>( &self, device: D, desired_spec: &AudioSpecDesired, get_callback: F ) -> PixResult<AudioDevice<CB>>
Opens and returns an audio capture device for recording.
The audio device starts out paused
. Call resume to start
recording and pause to stop recording.
Errors
If the renderer fails to open an audio device, then an error is returned.
Example
use pix_engine::prelude::*;
use std::{sync::mpsc, time::Duration};
struct Recording {
record_buffer: Vec<f32>,
pos: usize,
tx: mpsc::Sender<Vec<f32>>,
done: bool,
}
impl AudioCallback for Recording {
type Channel = f32;
fn callback(&mut self, input: &mut [Self::Channel]) {
if self.done {
return;
}
for x in input {
self.record_buffer[self.pos] = *x;
self.pos += 1;
if self.pos >= self.record_buffer.len() {
self.done = true;
self.tx
.send(self.record_buffer.clone())
.expect("could not send record buffer");
break;
}
}
}
}
struct MyApp;
const RECORDING_LENGTH_SECONDS: usize = 3;
impl PixEngine for MyApp {
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
let desired_spec = AudioSpecDesired {
freq: None, // default device frequency
channels: None, // default device channels
samples: None, // default sample size
};
let (tx, rx) = mpsc::channel();
let capture_device = s.open_capture(None, &desired_spec, |spec| {
Recording {
record_buffer: vec![
0.0;
spec.freq as usize
* RECORDING_LENGTH_SECONDS
* spec.channels as usize
],
pos: 0,
tx,
done: false,
}
})?;
// Start playback
capture_device.resume();
// Wait for recording to finish
let recorded_samples = rx.recv()?;
capture_device.pause();
// Handle recorded_samples
// Device stops playback when dropped.
Ok(())
}
}
source§impl PixState
impl PixState
sourcepub fn image_transformed<R1, R2, A, C, F>(
&mut self,
img: &Image,
src: R1,
dst: R2,
angle: A,
center: C,
flipped: F
) -> PixResult<()>
pub fn image_transformed<R1, R2, A, C, F>( &mut self, img: &Image, src: R1, dst: R2, angle: A, center: C, flipped: F ) -> PixResult<()>
Draw a transformed Image to the current canvas resized to the target rect
, optionally
rotated by an angle
about the center
point or flipped
. angle
can be in either
radians or degrees based on AngleMode
. PixState::image_tint
can optionally add a tint
color to the rendered image.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.angle_mode(AngleMode::Degrees);
let image = Image::from_file("./some_image.png")?;
let src = None; // Draw entire image instead of a sub-image
let dst = image.bounding_rect_offset([10, 10]); // Draw image at `(10, 10)`.
let angle = 10.0;
let center = point!(10, 10);
s.image_transformed(&image, src, dst, angle, center, Flipped::Horizontal)?;
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn focused(&self) -> bool
pub fn focused(&self) -> bool
Returns whether the current window target has focus. To check focus of a specific window, see
PixState::focused_window
.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
if s.focused() {
// Update screen only when focused
s.rect([0, 0, 100, 100])?;
}
Ok(())
}
sourcepub fn focused_window(&self, window_id: WindowId) -> bool
pub fn focused_window(&self, window_id: WindowId) -> bool
Returns whether a given window has focus. To check focus of a any window, see
PixState::focused
.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
if s.focused_window(s.window_id()) {
// Update screen only when focused
s.rect([0, 0, 100, 100])?;
}
Ok(())
}
sourcepub const fn delta_time(&self) -> Duration
pub const fn delta_time(&self) -> Duration
sourcepub fn elapsed(&self) -> Duration
pub fn elapsed(&self) -> Duration
The [Duration[ elapsed since application start.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
// Draw a blinking box, indepdendent of frame rate
if s.elapsed().as_millis() >> 9 & 1 > 0 {
s.rect([0, 0, 10, 10])?;
}
Ok(())
}
sourcepub const fn frame_count(&self) -> usize
pub const fn frame_count(&self) -> usize
The total number of frames rendered since application start.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
// Create a strobe effect, dependent on frame rate
if s.frame_count() % 5 == 0 {
s.rect([0, 0, 10, 10])?;
}
Ok(())
}
sourcepub fn redraw(&mut self)
pub fn redraw(&mut self)
Run the render loop 1 time by calling PixEngine::on_update
.
This can be used to only redraw in response to user actions such as
PixEngine::on_mouse_pressed
or PixEngine::on_key_pressed
.
Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
s.run(false); // Disable render loop
Ok(())
}
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
// Step one frame draw at a time on each space press
// Useful for debugging frame-by-frame
if let Key::Space = event.key {
s.redraw();
return Ok(true);
}
Ok(false)
sourcepub fn run_times(&mut self, n: usize)
pub fn run_times(&mut self, n: usize)
Run the render loop N times by calling PixEngine::on_update
.
This can be used to only redraw in response to user actions such as
PixEngine::on_mouse_pressed
or PixEngine::on_key_pressed
.
Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
s.run(false); // Disable render loop
Ok(())
}
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
// Step one frame draw at a time on each space press
// Useful for debugging by multiple frames at a time
if let Key::Space = event.key {
s.run_times(4);
return Ok(true);
}
Ok(false)
sourcepub const fn avg_frame_rate(&self) -> f32
pub const fn avg_frame_rate(&self) -> f32
The average frames per second rendered.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text(format!("FPS: {}", s.avg_frame_rate()))?;
Ok(())
sourcepub fn quit(&mut self)
pub fn quit(&mut self)
Trigger application quit.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
if s.button("Quit?")? {
s.quit();
}
Ok(())
sourcepub fn abort_quit(&mut self)
pub fn abort_quit(&mut self)
Abort application quit and resume render loop by calling PixEngine::on_update
.
Example
fn on_stop(&mut self, s: &mut PixState) -> PixResult<()> {
if self.has_unsaved_changes {
self.prompt_save_dialog = true;
s.abort_quit();
}
Ok(())
source§impl PixState
impl PixState
sourcepub fn background<C>(&mut self, color: C)
pub fn background<C>(&mut self, color: C)
sourcepub fn stroke_weight(&mut self, weight: u16)
pub fn stroke_weight(&mut self, weight: u16)
Sets the width used to draw lines on the canvas.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.stroke(Color::BLUE);
s.stroke_weight(2);
// Draws a 2-pixel wide diagonal line
s.line(line_![0, 0, 100, 100])?;
Ok(())
}
sourcepub fn font_style(&mut self, style: FontStyle)
pub fn font_style(&mut self, style: FontStyle)
sourcepub fn font_family(&mut self, font: Font) -> PixResult<()>
pub fn font_family(&mut self, font: Font) -> PixResult<()>
Set the font family for drawing to the current canvas.
Errors
If the renderer fails to load the given font size from the currently loaded font data, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.font_family(Font::NOTO)?;
s.text("Some NOTO family text")?;
s.font_family(Font::from_file("Custom font", "./custom_font.ttf"))?;
s.text("Some custom family text")?;
Ok(())
}
sourcepub fn text_shadow<D>(&mut self, distance: D)
pub fn text_shadow<D>(&mut self, distance: D)
Sets the text shadow distance used to draw text on the canvas.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text_shadow(2);
// Draws a 2-pixel offset shhadow
s.text("Shadowed")?;
Ok(())
}
sourcepub fn smooth(&mut self, val: bool)
pub fn smooth(&mut self, val: bool)
Enable or disable the anti-alias option used for drawing shapes on the canvas. smooth
is
enabled by default.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
// Draws a anti-aliased diagonal line
s.smooth(true);
s.line(line_![0, 0, 100, 100])?;
// Disables anti-aliasing
s.smooth(false);
s.line(line_![0, 0, 100, 100])?;
Ok(())
}
sourcepub fn bezier_detail(&mut self, detail: i32)
pub fn bezier_detail(&mut self, detail: i32)
Set the resolution at which PixState::bezier
curves are displayed. The default is 20
.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.bezier_detail(5);
s.stroke(Color::RED);
s.bezier([[85, 20], [10, 10], [90, 90], [15, 80]])?;
Ok(())
}
sourcepub fn wrap<W>(&mut self, width: W)
pub fn wrap<W>(&mut self, width: W)
Sets the wrap width used to draw text on the canvas. None
disables text wrap.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
// Renders as (depending on font width):
//
// Lorem ipsum
// dollor sit amet,
// consetetur
// sadipscing
// elitr, sed diam
s.wrap(100);
s.text("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam")?;
// Disable wrapping
s.wrap((None));
s.text("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam")?;
Ok(())
}
sourcepub fn clip<R>(&mut self, rect: R) -> PixResult<()>
pub fn clip<R>(&mut self, rect: R) -> PixResult<()>
Sets the clip Rect used by the renderer to draw to the current canvas. None
disables
clipping.
Errors
If the current render target is closed or dropped, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.clip(rect![0, 0, 100, 100])?;
// Renders a quarter pie-slice with radius 100
s.circle([100, 100, 200, 200])?;
Ok(())
}
sourcepub fn fullscreen(&mut self, val: bool) -> PixResult<()>
pub fn fullscreen(&mut self, val: bool) -> PixResult<()>
Set the application to fullscreen or not.
Errors
If the current render target is closed or dropped or the renderer fails to set fullscreen, then an error is returned.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
if let Key::Return = event.key {
s.fullscreen(true)?;
return Ok(true);
}
Ok(false)
}
sourcepub fn toggle_fullscreen(&mut self) -> PixResult<()>
pub fn toggle_fullscreen(&mut self) -> PixResult<()>
Toggle fullscreen.
Errors
If the current render target is closed or dropped or the renderer fails to toggle fullscreen, then an error is returned.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
if let Key::Return = event.key {
s.toggle_fullscreen()?;
return Ok(true);
}
Ok(false)
}
sourcepub fn vsync(&mut self, val: bool) -> PixResult<WindowId>
pub fn vsync(&mut self, val: bool) -> PixResult<WindowId>
Set the window to synchronize frame rate to the screens refresh rate (VSync
).
Note
Due to the current limitation with changing VSync
at runtime, this method creates a new
window using the properties of the current window and returns the new WindowId
.
If you are storing and interacting with this window using the WindowId
, make sure to
use the newly returned WindowId
.
Errors
If the current render target is closed or dropped or the renderer fails to set vsync, then an error is returned.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
if let Key::Return = event.key {
s.vsync(true)?;
return Ok(true);
}
Ok(false)
}
sourcepub fn toggle_vsync(&mut self) -> PixResult<WindowId>
pub fn toggle_vsync(&mut self) -> PixResult<WindowId>
Toggle synchronizing frame rate to the screens refresh rate (VSync
).
Note
Due to the current limitation with changing VSync
at runtime, this method creates a new
window using the properties of the current window and returns the new WindowId
.
If you are storing and interacting with this window using the WindowId
, make sure to
use the newly returned WindowId
.
Errors
If the current render target is closed or dropped or the renderer fails to toggle vsync, then an error is returned.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
if let Key::Return = event.key {
s.toggle_vsync()?;
return Ok(true);
}
Ok(false)
}
sourcepub fn cursor<C>(&mut self, cursor: C) -> PixResult<()>
pub fn cursor<C>(&mut self, cursor: C) -> PixResult<()>
Set the mouse cursor to a predefined symbol or image. None
hides the cursor.
Errors
If the renderer fails to set the cursor or load it from an image file, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text("Hover me")?;
if s.hovered() {
s.cursor(Cursor::hand())?;
} else {
s.cursor(Cursor::arrow())?;
}
Ok(())
}
sourcepub fn disable(&mut self, disabled: bool)
pub fn disable(&mut self, disabled: bool)
Disables any UI elements drawn after this is called, preventing them from being interacted with.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
if s.button("Disable UI")? {
s.disable(true);
}
s.checkbox("Disabled checkbox", &mut self.checkbox)?;
Ok(())
}
sourcepub fn running(&mut self) -> bool
pub fn running(&mut self) -> bool
Whether the render loop is running or not.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
if let Key::Return = event.key {
// Toggle pausing rendering
let running = s.running();
s.run(!running);
return Ok(true);
}
Ok(false)
}
sourcepub fn run(&mut self, val: bool)
pub fn run(&mut self, val: bool)
Pause or resume the render loop called by PixEngine::on_update
.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
if let Key::Return = event.key {
// Toggle rendering
let running = s.running();
s.run(running);
return Ok(true);
}
Ok(false)
}
sourcepub fn show_frame_rate(&mut self, show: bool)
pub fn show_frame_rate(&mut self, show: bool)
Set whether to show the current frame rate per second in the title or not.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
if let Key::Return = event.key {
s.show_frame_rate(true);
return Ok(true);
}
Ok(false)
}
sourcepub fn target_frame_rate(&mut self) -> Option<usize>
pub fn target_frame_rate(&mut self) -> Option<usize>
Get the target frame rate to render at.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
if let Key::Down = event.key {
let target = s.target_frame_rate().unwrap_or(60);
s.frame_rate(target - 10);
return Ok(true);
}
Ok(false)
}
sourcepub fn frame_rate<R>(&mut self, frame_rate: R)
pub fn frame_rate<R>(&mut self, frame_rate: R)
Set a target frame rate to render at, controls how often PixEngine::on_update
is
called. None
clears the target frame rate.
Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
// Target a lower FPS than natively possible
s.frame_rate(30);
Ok(())
}
sourcepub fn scale(&mut self, x: f32, y: f32) -> PixResult<()>
pub fn scale(&mut self, x: f32, y: f32) -> PixResult<()>
Set the rendering scale of the current canvas. Drawing coordinates are scaled by x/y factors before being drawn to the canvas.
Errors
If the current render target is closed or dropped, or (x, y
) contain invalid values,
then an error is returned.
Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
if let Key::Plus = event.key {
s.scale(2.0, 2.0)?;
return Ok(true);
}
Ok(false)
}
sourcepub fn ellipse_mode(&mut self, mode: EllipseMode)
pub fn ellipse_mode(&mut self, mode: EllipseMode)
sourcepub fn image_mode(&mut self, mode: ImageMode)
pub fn image_mode(&mut self, mode: ImageMode)
sourcepub fn image_tint<C>(&mut self, tint: C)
pub fn image_tint<C>(&mut self, tint: C)
sourcepub fn arc_mode(&mut self, mode: ArcMode)
pub fn arc_mode(&mut self, mode: ArcMode)
Change the way arcs are drawn.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
// Draw arc as a open, unfilled pie segment using only the `stroke` (The default)
s.arc_mode(ArcMode::Default);
s.arc([100, 100], 20, 0, 180)?;
s.arc_mode(ArcMode::Pie);
// Draw arc as a closed pie segment using both `fill` and `stroke`
s.arc([200, 200], 20, 0, 180)?;
Ok(())
}
sourcepub fn angle_mode(&mut self, mode: AngleMode)
pub fn angle_mode(&mut self, mode: AngleMode)
Change the way angles are interpreted for rotation and matrix transformations.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.angle_mode(AngleMode::Degrees);
let angle = 10.0;
let center = point!(10, 10);
s.text_transformed("Rotated text", angle, center, None)?;
Ok(())
}
sourcepub fn blend_mode(&mut self, mode: BlendMode)
pub fn blend_mode(&mut self, mode: BlendMode)
Change the way textures are blended together.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.blend_mode(BlendMode::Blend);
// Draw image with alpha blended with background
s.image(&Image::from_file("./some_image.png")?, [0, 0])?;
Ok(())
}
sourcepub fn push(&mut self)
pub fn push(&mut self)
Saves the current draw settings and transforms.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLUE);
s.stroke(Color::WHITE);
s.push(); // Save settings
s.fill(Color::RED);
s.stroke(Color::BLACK);
s.rect([0, 0, 100, 100])?;
s.pop(); // Restore settings
// Rectangle is blue with a white outline
s.rect([0, 0, 100, 100])?;
Ok(())
}
sourcepub fn pop(&mut self)
pub fn pop(&mut self)
Restores the previous draw settings and transforms, if present. If the settings stack is empty, the settings will remain unchanged.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.fill(Color::BLUE);
s.stroke(Color::WHITE);
s.push(); // Save settings
s.fill(Color::RED);
s.stroke(Color::BLACK);
s.rect([0, 0, 100, 100])?;
s.pop(); // Restore settings
// Rectangle is blue with a white outline
s.rect([0, 0, 100, 100])?;
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn title(&self) -> &str
pub fn title(&self) -> &str
Get the current window title.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text(format!("Window title: {}", s.title()))?;
Ok(())
}
sourcepub fn mouse_pos(&self) -> Point<i32>
pub fn mouse_pos(&self) -> Point<i32>
Returns the current mouse position coordinates this frame as (x, y)
.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
// Draw 100x100 rectangle that follows the mouse
s.rect(rect![s.mouse_pos(), 100, 100])?;
Ok(())
}
sourcepub fn pmouse_pos(&self) -> Point<i32>
pub fn pmouse_pos(&self) -> Point<i32>
Returns the previous mouse position coordinates last frame as (x, y)
.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
// Draw 100x100 rectangle that follows the mouse last frame
// Creates a yoyo-like effect
s.rect(rect![s.pmouse_pos(), 100, 100])?;
Ok(())
}
sourcepub fn mouse_pressed(&self) -> bool
pub fn mouse_pressed(&self) -> bool
sourcepub fn mouse_clicked(&self, btn: Mouse) -> bool
pub fn mouse_clicked(&self, btn: Mouse) -> bool
sourcepub fn mouse_dbl_clicked(&self, btn: Mouse) -> bool
pub fn mouse_dbl_clicked(&self, btn: Mouse) -> bool
sourcepub fn mouse_down(&self, btn: Mouse) -> bool
pub fn mouse_down(&self, btn: Mouse) -> bool
Returns a list of the current mouse buttons pressed this frame.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
// Only trigger if both buttons are pressed
if s.mouse_buttons().contains(&Mouse::Left)
&& s.mouse_buttons().contains(&Mouse::Right)
{
s.background(Color::random());
}
Ok(())
}
sourcepub fn key_pressed(&self) -> bool
pub fn key_pressed(&self) -> bool
sourcepub const fn keys(&self) -> &HashSet<Key>
pub const fn keys(&self) -> &HashSet<Key>
Returns a list of the current keys pressed this frame.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
if s.keys().contains(&Key::Space) && s.keys().contains(&Key::Up) {
s.background(Color::random());
}
Ok(())
}
sourcepub const fn keymod_down(&self, keymod: KeyMod) -> bool
pub const fn keymod_down(&self, keymod: KeyMod) -> bool
sourcepub const fn keymod(&self) -> &KeyMod
pub const fn keymod(&self) -> &KeyMod
Returns a list of the current key modifiers pressed this frame.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
if s.keymod().intersects(KeyMod::SHIFT | KeyMod::CTRL)
&& s.key_down(Key::Space)
{
s.background(Color::random());
}
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn poll_event(&mut self) -> Option<Event>
pub fn poll_event(&mut self) -> Option<Event>
Polls for events from the underlying renderer.
sourcepub fn open_controller(&mut self, id: ControllerId) -> PixResult<()>
pub fn open_controller(&mut self, id: ControllerId) -> PixResult<()>
Open a controller with a given ID to start handling events.
Errors
If the ControllerId
is invalid or the renderer fails to open the controller, then an
error is returned.
sourcepub fn close_controller(&mut self, id: ControllerId)
pub fn close_controller(&mut self, id: ControllerId)
Close a controller with a given ID to stop handling events.
source§impl PixState
impl PixState
sourcepub fn texture<R1, R2>(
&mut self,
texture_id: TextureId,
src: R1,
dst: R2
) -> PixResult<()>
pub fn texture<R1, R2>( &mut self, texture_id: TextureId, src: R1, dst: R2 ) -> PixResult<()>
Draw a portion src
of a texture to the current render target translated and resized to
the target dst
. Passing None
for src
renders the entire texture. Passing None
for
dst
renders to the maximum size of the render target.
Note
It’s possible to render one texture onto another texture, but currently they both have to
have been created in the same window. Attempting to render to a texture created with
another window will result in a [Error::InvalidTexture
]. This restriction may be
lifted in the future.
Errors
Returns an error for any of the following: - The current render target is closed or dropped. - The texture being rendered has been dropped. - The target texture is the same as the texture being rendered. - The renderer fails to draw to the texture.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.set_texture_target(self.texture_id)?;
s.background(Color::random());
s.text("Rendered texture!")?;
s.clear_texture_target();
let src = rect![10, 10, 100, 100]; // Render a sub-section of the texture
// translate and scale texture
let dst = rect![200, 200, 200, 200];
s.texture(self.texture_id, src, dst)?;
Ok(())
}
sourcepub fn texture_transformed<R1, R2, C, F>(
&mut self,
texture_id: TextureId,
src: R1,
dst: R2,
angle: f64,
center: C,
flipped: F
) -> PixResult<()>
pub fn texture_transformed<R1, R2, C, F>( &mut self, texture_id: TextureId, src: R1, dst: R2, angle: f64, center: C, flipped: F ) -> PixResult<()>
Draw a transformed portion src
of a texture to the current render target translated and
resized to the target dst
, optionally rotated by an angle
about a center
point or
flipped
. angle
can be in either radians or degrees based on AngleMode
. Passing
None
for src
renders the entire texture. Passing None
for dst
renders to the
maximum size of the render target. PixState::image_tint
can optionally add a tint color
to the rendered texture.
Note
It’s possible to render one texture onto another texture, but currently they both have to
have been created in the same window. Attempting to render to a texture created with
another window will result in a [Error::InvalidTexture
]. This restriction may be
lifted in the future.
Errors
Returns an error for any of the following: - The current render target is closed or dropped. - The texture being rendered has been dropped. - The target texture is the same as the texture being rendered. - The renderer fails to draw to the texture.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.set_texture_target(self.texture_id)?;
s.background(Color::random());
s.text("Rendered texture!")?;
s.clear_texture_target();
let src = None;
// translate and scale texture
let dst = rect![200, 200, 200, 200];
let angle = 10.0;
let center = point!(10, 10);
s.texture_transformed(
self.texture_id,
src,
dst,
angle,
center,
Flipped::Horizontal,
)?;
Ok(())
}
sourcepub fn create_texture<F>(
&mut self,
width: u32,
height: u32,
format: F
) -> PixResult<TextureId>
pub fn create_texture<F>( &mut self, width: u32, height: u32, format: F ) -> PixResult<TextureId>
Constructs a Texture
to render to. Passing None
for PixelFormat
will use
PixelFormat::default
. The texture will be created and tied to the current window
target. To create a texture for a window other than the primary window, call
[PixState::set_window
].
Errors
If the current window target is closed or invalid, or the texture dimensions are invalid, then an error is returned.
Note
Textures are automatically dropped when the window they were created in is closed due to an
implicit lifetime that the texture can not outlive the window it was created for. Calling
this method will create a texture for the current window_target
, which can only be
changed using the PixState::set_window_target
method. It is the responsibility of the
caller to manage created textures and call PixState::delete_texture
when a texture
resource is no longer needed and to ensure that texture methods are not called for a given
window after it has been closed, otherwise an error will be returned.
This constraint arises due to lifetime issues with SDL textures, See https://github.com/Rust-SDL2/rust-sdl2/issues/1107 for more details.
Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
self.texture_id = s.create_texture(
s.width()? / 2,
s.height()? / 2,
PixelFormat::Rgb,
)?;
Ok(())
}
sourcepub fn delete_texture(&mut self, texture_id: TextureId) -> PixResult<()>
pub fn delete_texture(&mut self, texture_id: TextureId) -> PixResult<()>
Delete a Texture
.
Errors
If the current window target is closed or invalid, or the texture has already been dropped, then an error is returned.
Note
Currently, it is up to the caller to manage valid textures. Textures become invalid
whenever the window_target
they were created in has been closed. Calling any texture
methods with an invalid TextureId
will result in an error.
This constraint arises due to lifetime issues with SDL textures, See https://github.com/Rust-SDL2/rust-sdl2/issues/1107 for more details.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
// A more polished implementation would manage state in `self` to avoid re-creating and
// destroying textures every frame
let texture_id = s.create_texture(500, 600, PixelFormat::Rgb)?;
// Render things
s.delete_texture(texture_id)?;
Ok(())
}
sourcepub fn update_texture<R, P>(
&mut self,
texture_id: TextureId,
rect: R,
pixels: P,
pitch: usize
) -> PixResult<()>
pub fn update_texture<R, P>( &mut self, texture_id: TextureId, rect: R, pixels: P, pitch: usize ) -> PixResult<()>
Update the Texture
with a u8 slice of pixel data. Passing None
for rect
updates
the entire texture. pitch
is the number of bytes in a row of pixels data including
padding between lines.
Errors
If the window in which the texture was created is closed, or the renderer fails to update to the texture, then an error is returned.
Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
self.texture_id = s.create_texture(500, 600, None)?;
let image = Image::from_file("./some_image.png")?;
s.update_texture(self.texture_id, None, image.as_bytes(), image.pitch())?;
Ok(())
}
sourcepub fn set_texture_target(&mut self, id: TextureId) -> PixResult<()>
pub fn set_texture_target(&mut self, id: TextureId) -> PixResult<()>
Set a Texture
as the priamry target for drawing operations. Pushes current settings and UI
cursor to the stack, so any changes made while a texture target is set will be in effect
until [PixState::reset_texture_target
] is called.
Errors
If the target has been dropped or is invalid, then an error is returned.
Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
self.texture_id = s.create_texture(500, 600, None)?;
s.set_texture_target(self.texture_id)?;
s.background(Color::random());
s.text("Rendered texture!")?;
s.clear_texture_target();
Ok(())
}
sourcepub fn clear_texture_target(&mut self)
pub fn clear_texture_target(&mut self)
Clears Texture
target back to the primary canvas for drawing operations. Pops previous
settings and UI cursor off the stack, so that changes made while texture target was set are
reverted.
source§impl PixState
impl PixState
sourcepub fn window(&mut self) -> WindowBuilder<'_>
pub fn window(&mut self) -> WindowBuilder<'_>
Create a new WindowBuilder
.
sourcepub fn close_window(&mut self, id: WindowId) -> PixResult<()>
pub fn close_window(&mut self, id: WindowId) -> PixResult<()>
Close a window.
Errors
If the window has already been closed or is invalid, then an error is returned.
sourcepub fn dimensions(&self) -> PixResult<(u32, u32)>
pub fn dimensions(&self) -> PixResult<(u32, u32)>
The dimensions of the current render target (window or texture) as (width, height)
.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn window_dimensions(&self) -> PixResult<(u32, u32)>
pub fn window_dimensions(&self) -> PixResult<(u32, u32)>
The dimensions of the current window target as (width, height)
.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn set_window_dimensions(&mut self, dimensions: (u32, u32)) -> PixResult<()>
pub fn set_window_dimensions(&mut self, dimensions: (u32, u32)) -> PixResult<()>
Set the dimensions of the current window target from (width, height)
.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn window_position(&self) -> PixResult<(i32, i32)>
pub fn window_position(&self) -> PixResult<(i32, i32)>
The position of the current window target as (x, y)
.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn viewport(&mut self) -> PixResult<Rect<i32>>
pub fn viewport(&mut self) -> PixResult<Rect<i32>>
Returns the rendering viewport of the current render target.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn set_viewport<R>(&mut self, rect: R) -> PixResult<()>
pub fn set_viewport<R>(&mut self, rect: R) -> PixResult<()>
Set the rendering viewport of the current render target.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn clear_viewport(&mut self) -> PixResult<()>
pub fn clear_viewport(&mut self) -> PixResult<()>
Clears the rendering viewport of the current render target back to the entire target.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn width(&self) -> PixResult<u32>
pub fn width(&self) -> PixResult<u32>
The width of the current render target.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn window_width(&self) -> PixResult<u32>
pub fn window_width(&self) -> PixResult<u32>
The width of the current window.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn set_window_width(&mut self, width: u32) -> PixResult<()>
pub fn set_window_width(&mut self, width: u32) -> PixResult<()>
Set the width of the current window.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn height(&self) -> PixResult<u32>
pub fn height(&self) -> PixResult<u32>
The height of the current render target.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn window_height(&self) -> PixResult<u32>
pub fn window_height(&self) -> PixResult<u32>
The height of the current window.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn set_window_height(&mut self, height: u32) -> PixResult<()>
pub fn set_window_height(&mut self, height: u32) -> PixResult<()>
Set the height of the current window.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn window_x(&self) -> PixResult<i32>
pub fn window_x(&self) -> PixResult<i32>
The x of the current window.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn window_y(&self) -> PixResult<i32>
pub fn window_y(&self) -> PixResult<i32>
The y of the current window.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn window_center(&self) -> PixResult<Point<i32>>
pub fn window_center(&self) -> PixResult<Point<i32>>
sourcepub fn display_dimensions(&self) -> PixResult<(u32, u32)>
pub fn display_dimensions(&self) -> PixResult<(u32, u32)>
The dimensions of the primary display as (width, height)
.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn display_width(&self) -> PixResult<u32>
pub fn display_width(&self) -> PixResult<u32>
The width of the primary display.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn display_height(&self) -> PixResult<u32>
pub fn display_height(&self) -> PixResult<u32>
The height of the primary display.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn show_window(&mut self) -> PixResult<()>
pub fn show_window(&mut self) -> PixResult<()>
Show the current window target if it is hidden.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn hide_window(&mut self) -> PixResult<()>
pub fn hide_window(&mut self) -> PixResult<()>
Hide the current window target if it is shown.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn set_window_target(&mut self, id: WindowId) -> PixResult<()>
pub fn set_window_target(&mut self, id: WindowId) -> PixResult<()>
Set a Window
as the primary target for drawing operations. Pushes current settings and UI
cursor to the stack, so any changes made while a window target is set will be in effect
until PixState::reset_window_target
is called.
Errors
If the window has been closed or is invalid, then an error is returned.
sourcepub fn reset_window_target(&mut self)
pub fn reset_window_target(&mut self)
Reset Window
target back to the primary window for drawing operations. Pops previous
settings and UI cursor off the stack, so that changes made while window target was set are
reverted.
source§impl PixState
impl PixState
sourcepub fn same_line<O>(&mut self, offset: O)
pub fn same_line<O>(&mut self, offset: O)
Reset current UI rendering position back to the previous line with item padding, and continue with horizontal layout.
You can optionally change the item padding, or set a different horizontal or vertical
position by passing in an offset
.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text("Text")?;
s.same_line(None);
s.text("Same line")?;
Ok(())
}
sourcepub fn next_width(&mut self, width: u32)
pub fn next_width(&mut self, width: u32)
Change the default width of the next rendered element for elements that typically take up the remaining width of the window/frame they are rendered in.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.next_width(200);
if s.button("Button")? {
// was clicked
}
Ok(())
}
sourcepub fn tab_bar<S, I, F>(
&mut self,
label: S,
tabs: &[I],
selected: &mut I,
f: F
) -> PixResult<bool>
pub fn tab_bar<S, I, F>( &mut self, label: S, tabs: &[I], selected: &mut I, f: F ) -> PixResult<bool>
Draw a tabbed view to the current canvas. It accepts a list of tabs to be rendered, which
one is selected and a closure that is passed the current tab and &mut PixState
which you can use to draw all the standard drawing primitives and
change any drawing settings. Settings changed inside the closure will not persist. Returns
true
if a tab selection was changed.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.tab_bar(
"Tab bar",
&["Tab 1", "Tab 2"],
&mut self.selected,
|tab: &&str, s: &mut PixState| {
match tab {
&"Tab 1" => {
s.text("Tab 1")?;
s.separator();
s.text("Some Content")?;
}
&"Tab 2" => {
s.next_width(200);
if s.button("Click me")? {
// was clicked
}
}
_ => (),
}
Ok(())
}
)?;
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn separator(&mut self) -> PixResult<()>
pub fn separator(&mut self) -> PixResult<()>
Draw a horizontal or vertical separator to the current canvas.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text("Some text")?;
s.separator()?;
s.text("Some other text")?;
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn clipboard_text(&self) -> String
pub fn clipboard_text(&self) -> String
Get clipboard text from the system clipboard.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
println!("Current clipboard text: {}", s.clipboard_text());
Ok(())
}
sourcepub fn set_clipboard_text<S>(&self, value: S) -> PixResult<()>
pub fn set_clipboard_text<S>(&self, value: S) -> PixResult<()>
sourcepub fn open_url<S>(&self, url: S) -> PixResult<()>
pub fn open_url<S>(&self, url: S) -> PixResult<()>
Open a URL in the default system browser.
Errors
If the renderer fails to launch an external application, then an error is returned. Note,
there is no way to know if the URL opened successfully or not. An Ok
result only means an
application was successfully launched to handle the URL.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
if s.button("Open Homepage")? {
s.open_url("https://example.com")?;
}
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn text_field<L>(&mut self, label: L, value: &mut String) -> PixResult<bool>
pub fn text_field<L>(&mut self, label: L, value: &mut String) -> PixResult<bool>
sourcepub fn advanced_text_field<L, H>(
&mut self,
label: L,
hint: H,
value: &mut String,
filter: Option<fn(_: char) -> bool>
) -> PixResult<bool>
pub fn advanced_text_field<L, H>( &mut self, label: L, hint: H, value: &mut String, filter: Option<fn(_: char) -> bool> ) -> PixResult<bool>
Draw a text field with a placeholder hint to the current canvas.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.advanced_text_field(
"Filtered Text Field w/ hint",
"placeholder",
&mut self.text_field,
Some(char::is_numeric),
)?;
Ok(())
}
sourcepub fn text_area<L>(
&mut self,
label: L,
width: u32,
height: u32,
value: &mut String
) -> PixResult<bool>
pub fn text_area<L>( &mut self, label: L, width: u32, height: u32, value: &mut String ) -> PixResult<bool>
sourcepub fn advanced_text_area<L, H>(
&mut self,
label: L,
hint: H,
width: u32,
height: u32,
value: &mut String,
filter: Option<fn(_: char) -> bool>
) -> PixResult<bool>
pub fn advanced_text_area<L, H>( &mut self, label: L, hint: H, width: u32, height: u32, value: &mut String, filter: Option<fn(_: char) -> bool> ) -> PixResult<bool>
Draw a text area field with a placeholder hint to the current canvas.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.advanced_text_area(
"Filtered Text Area w/ hint",
"placeholder",
200,
100,
&mut self.text_area,
Some(char::is_alphabetic),
)?;
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn select_box<S, I>(
&mut self,
label: S,
selected: &mut usize,
items: &[I],
displayed_count: usize
) -> PixResult<bool>
pub fn select_box<S, I>( &mut self, label: S, selected: &mut usize, items: &[I], displayed_count: usize ) -> PixResult<bool>
Draw a select box the current canvas that returns true
when selection is changed.
Maximum displayed count of 100.
Errors
If the renderer fails to draw to the current render target, or if displayed_count
is
greater than MAX_DISPLAYED
then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
let items = ["Item 1", "Item 2", "Item 3"];
let displayed_count = 4;
if s.select_box("Select Box", &mut self.select_box, &items, displayed_count)? {
// selection changed
}
Ok(())
}
sourcepub fn select_list<S, I>(
&mut self,
label: S,
selected: &mut usize,
items: &[I],
displayed_count: usize
) -> PixResult<bool>
pub fn select_list<S, I>( &mut self, label: S, selected: &mut usize, items: &[I], displayed_count: usize ) -> PixResult<bool>
Draw a select list to the current canvas with a scrollable region that returns true
when
selection is changed.
Errors
If the renderer fails to draw to the current render target, or if displayed_count
is
greater than MAX_DISPLAYED
then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
let items = ["Item 1", "Item 2", "Item 3"];
let displayed_count = 4;
if s.select_list("Select List", &mut self.select_list, &items, displayed_count)? {
// Selection changed
}
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn drag<T, L>(
&mut self,
label: L,
value: &mut T,
speed: T
) -> PixResult<bool>
pub fn drag<T, L>( &mut self, label: L, value: &mut T, speed: T ) -> PixResult<bool>
Draw a draggable number widget to the current canvas.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.drag("Drag Int", &mut self.int, 1)?;
s.drag("Drag Float", &mut self.float, 0.005)?;
Ok(())
}
sourcepub fn advanced_drag<'a, T, L>(
&mut self,
label: L,
value: &mut T,
speed: T,
min: T,
max: T,
formatter: Option<fn(_: &T) -> Cow<'a, str>>
) -> PixResult<bool>
pub fn advanced_drag<'a, T, L>( &mut self, label: L, value: &mut T, speed: T, min: T, max: T, formatter: Option<fn(_: &T) -> Cow<'a, str>> ) -> PixResult<bool>
Draw an advanced draggable number widget to the current canvas.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.advanced_drag(
"Advanced Drag",
&mut self.advanced_drag,
0.005,
0.0,
1.0,
Some(|val| format!("{:.3}", val).into()),
)?;
Ok(())
}
sourcepub fn slider<T, L>(
&mut self,
label: L,
value: &mut T,
min: T,
max: T
) -> PixResult<bool>
pub fn slider<T, L>( &mut self, label: L, value: &mut T, min: T, max: T ) -> PixResult<bool>
Draw a slider widget to the current canvas.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.slider("Slider Int", &mut self.int, -5, 5)?;
s.slider("Slider Float", &mut self.float, 0.0, 1.0)?;
Ok(())
}
sourcepub fn advanced_slider<'a, T, L>(
&mut self,
label: L,
value: &mut T,
min: T,
max: T,
formatter: Option<fn(_: &T) -> Cow<'a, str>>
) -> PixResult<bool>
pub fn advanced_slider<'a, T, L>( &mut self, label: L, value: &mut T, min: T, max: T, formatter: Option<fn(_: &T) -> Cow<'a, str>> ) -> PixResult<bool>
Draw an advanced slider widget to the current canvas.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Panics
Panics if value
, min
, or max
can not be cast to a floating point value.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.advanced_slider(
"Advanced Slider",
&mut self.advanced_slider,
0.0,
1.0,
Some(|val| format!("ratio = {:.3}", val).into()),
)?;
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn size_of<S: AsRef<str>>(&self, text: S) -> PixResult<(u32, u32)>
pub fn size_of<S: AsRef<str>>(&self, text: S) -> PixResult<(u32, u32)>
Return the dimensions of given text for drawing to the current canvas.
Errors
If the renderer fails to load the current font, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
let text = "Some text";
let (w, h) = s.size_of(text)?;
// Draw a box behind the text
s.rect(rect![s.cursor_pos() - 10, w as i32 + 20, h as i32 + 20]);
s.text(text)?;
Ok(())
}
sourcepub fn text<S>(&mut self, text: S) -> PixResult<(u32, u32)>
pub fn text<S>(&mut self, text: S) -> PixResult<(u32, u32)>
Draw body text to the current canvas.
Returns the rendered (width, height)
of the text, including any newlines or text
wrapping.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text("Text")?;
Ok(())
}
sourcepub fn heading<S>(&mut self, text: S) -> PixResult<(u32, u32)>
pub fn heading<S>(&mut self, text: S) -> PixResult<(u32, u32)>
Draw heading text to the current canvas.
Returns the rendered (width, height)
of the text, including any newlines or text
wrapping.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.heading("Heading")?;
Ok(())
}
sourcepub fn monospace<S>(&mut self, text: S) -> PixResult<(u32, u32)>
pub fn monospace<S>(&mut self, text: S) -> PixResult<(u32, u32)>
Draw monospace text to the current canvas.
Returns the rendered (width, height)
of the text, including any newlines or text
wrapping.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.monospace("Monospace")?;
Ok(())
}
sourcepub fn text_transformed<S, A, C, F>(
&mut self,
text: S,
angle: A,
center: C,
flipped: F
) -> PixResult<(u32, u32)>
pub fn text_transformed<S, A, C, F>( &mut self, text: S, angle: A, center: C, flipped: F ) -> PixResult<(u32, u32)>
Draw transformed text to the current canvas, optionally rotated about a center
by angle
or flipped
. angle
can be in radians or degrees depending on AngleMode
.
Returns the rendered (width, height)
of the text, including any newlines or text
wrapping.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.angle_mode(AngleMode::Degrees);
let angle = 10.0;
let center = point!(10, 10);
s.text_transformed("Transformed text", angle, center, Flipped::Horizontal)?;
Ok(())
}
sourcepub fn bullet<S>(&mut self, text: S) -> PixResult<(u32, u32)>
pub fn bullet<S>(&mut self, text: S) -> PixResult<(u32, u32)>
Draw bulleted text to the current canvas.
Returns the rendered (width, height)
of the text, including any newlines or text
wrapping.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.bullet("Bulleted text")?;
Ok(())
}
Draw a text menu to the current canvas which returns true when clicked.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
sourcepub fn collapsing_tree<S, F>(&mut self, text: S, f: F) -> PixResult<bool>
pub fn collapsing_tree<S, F>(&mut self, text: S, f: F) -> PixResult<bool>
Draw a collapsing text tree to the current canvas which returns true when the bullet is not collapsed.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
sourcepub fn collapsing_header<S, F>(&mut self, text: S, f: F) -> PixResult<bool>
pub fn collapsing_header<S, F>(&mut self, text: S, f: F) -> PixResult<bool>
Draw a collapsing header to the current canvas which returns true when the tree is not collapsed.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
source§impl PixState
impl PixState
sourcepub fn help_marker<S>(&mut self, text: S) -> PixResult<()>
pub fn help_marker<S>(&mut self, text: S) -> PixResult<()>
Draw help marker text that, when hovered, displays a help box with text to the current canvas.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.help_marker("Help marker icon w/ tooltip")?;
Ok(())
}
sourcepub fn tooltip<S>(&mut self, text: S) -> PixResult<()>
pub fn tooltip<S>(&mut self, text: S) -> PixResult<()>
Draw tooltip box at the mouse cursor with text to the current canvas.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text("Hover me")?;
if s.hovered() {
s.tooltip("Basic tooltip")?;
}
Ok(())
}
sourcepub fn advanced_tooltip<S, R, F>(
&mut self,
label: S,
rect: R,
f: F
) -> PixResult<()>
pub fn advanced_tooltip<S, R, F>( &mut self, label: S, rect: R, f: F ) -> PixResult<()>
Draw an advanced tooltip box at the mouse cursor to the current canvas. It accepts a
closure that is passed &mut PixState
which you can use to draw all the
standard drawing primitives and change any drawing settings. Settings changed inside the
closure will not persist.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text("Hover me")?;
if s.hovered() {
s.advanced_tooltip(
"Tooltip",
rect![s.mouse_pos(), 200, 100],
|s: &mut PixState| {
s.background(Color::CADET_BLUE);
s.bullet("Advanced tooltip")?;
Ok(())
},
)?;
}
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn radio<S>(
&mut self,
label: S,
selected: &mut usize,
index: usize
) -> PixResult<bool>
pub fn radio<S>( &mut self, label: S, selected: &mut usize, index: usize ) -> PixResult<bool>
Draw a set of radio buttons to the current canvas.
Errors
If the renderer fails to draw to the current render target, then an error is returned.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.radio("Radio 1", &mut self.radio, 0)?;
s.radio("Radio 2", &mut self.radio, 1)?;
s.radio("Radio 3", &mut self.radio, 2)?;
Ok(())
}
source§impl PixState
impl PixState
sourcepub fn push_id<I>(&mut self, id: I)
pub fn push_id<I>(&mut self, id: I)
Push a new seed to the UI ID stack. Helps in generating unique widget identifiers that have the same text label. Pushing a unique ID to the stack will seed the hash of the label.
sourcepub const fn cursor_pos(&self) -> Point<i32>
pub const fn cursor_pos(&self) -> Point<i32>
Returns the current UI rendering position.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
let mut pos = s.cursor_pos();
pos.offset_y(20);
s.set_cursor_pos(pos);
s.text("Some text, offset down by 20 pixels")?;
Ok(())
}
sourcepub fn set_cursor_pos<P: Into<Point<i32>>>(&mut self, cursor: P)
pub fn set_cursor_pos<P: Into<Point<i32>>>(&mut self, cursor: P)
Set the current UI rendering position.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.set_cursor_pos(s.center()?);
s.rect_mode(RectMode::Center);
s.text("Centered text")?;
Ok(())
}
sourcepub fn set_column_offset(&mut self, offset: i32)
pub fn set_column_offset(&mut self, offset: i32)
Set the current UI rendering position column offset.
sourcepub fn reset_column_offset(&mut self)
pub fn reset_column_offset(&mut self)
Clears the current UI rendering position column offset.
sourcepub fn hovered(&self) -> bool
pub fn hovered(&self) -> bool
Returns whether the last item drawn is hovered with the mouse.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text("Hover me")?;
if s.hovered() {
s.tooltip("I'm a tooltip!");
}
Ok(())
}
sourcepub fn clicked(&self) -> bool
pub fn clicked(&self) -> bool
Returns whether the last item drawn was clicked with the left mouse button.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text("Hover me")?;
if s.clicked() {
println!("I was clicked!");
}
Ok(())
}
sourcepub fn dbl_clicked(&self) -> bool
pub fn dbl_clicked(&self) -> bool
Returns whether the last item drawn was double-clicked with the left mouse button.
Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
s.text("Hover me")?;
if s.dbl_clicked() {
println!("I was double clicked!");
}
Ok(())
}