Struct RenderWindow

Source
#[repr(C)]
pub struct RenderWindow { /* private fields */ }
Expand description

Window that can serve as a target for 2D drawing.

RenderWindow is the main type of the graphics module. It defines an OS window that can be painted using the other classes of the graphics module.

Implementations§

Source§

impl RenderWindow

Creation

Source

pub fn new<V: Into<VideoMode>, S: SfStrConv>( mode: V, title: S, style: Style, settings: &ContextSettings, ) -> SfResult<FBox<Self>>

Construct a new render window

This function creates the render window with the size and pixel depth defined in mode. An optional style can be passed to customize the look and behaviour of the window (borders, title bar, resizable, closable, …). If style contains Style::FULLSCREEN, then mode must be a valid video mode.

The fourth parameter is a pointer to a structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc.

§Arguments
  • mode - Video mode to use (defines the width, height and depth of the rendering area of the render window)
  • title - Title of the render window
  • style - Window style
  • settings - Additional settings for the underlying OpenGL context
Examples found in repository?
examples/custom-drawable.rs (lines 42-47)
41fn main() -> SfResult<()> {
42    let mut window = RenderWindow::new(
43        (800, 600),
44        "Custom drawable",
45        Style::CLOSE,
46        &Default::default(),
47    )?;
48    window.set_vertical_sync_enabled(true);
49
50    let bullet = Bullet::new();
51
52    'mainloop: loop {
53        while let Some(event) = window.poll_event() {
54            match event {
55                Event::Closed
56                | Event::KeyPressed {
57                    code: Key::Escape, ..
58                } => break 'mainloop,
59                _ => {}
60            }
61        }
62
63        window.clear(Color::BLACK);
64        window.draw(&bullet);
65        window.display()
66    }
67    Ok(())
68}
More examples
Hide additional examples
examples/resource-holder.rs (lines 62-67)
55fn main() -> SfResult<()> {
56    example_ensure_right_working_dir();
57
58    let mut tex_holder = ResourceHolder::<Texture, _>::default();
59    tex_holder.load("frank", "frank.jpeg")?;
60    let mut sb_holder = ResourceHolder::<SoundBuffer, _>::default();
61    sb_holder.load("canary", "canary.wav")?;
62    let mut rw = RenderWindow::new(
63        (800, 600),
64        "Resource holder test",
65        Style::CLOSE,
66        &Default::default(),
67    )?;
68    rw.set_vertical_sync_enabled(true);
69    let mut sound = Sound::with_buffer(sb_holder.get("canary"));
70    sound.play();
71    while rw.is_open() {
72        while let Some(ev) = rw.poll_event() {
73            match ev {
74                Event::Closed
75                | Event::KeyPressed {
76                    code: Key::Escape, ..
77                } => rw.close(),
78                _ => {}
79            }
80        }
81        rw.clear(Color::BLACK);
82        rw.draw(&Sprite::with_texture(tex_holder.get("frank")));
83        rw.display();
84    }
85    Ok(())
86}
examples/custom-shape.rs (lines 47-52)
46fn main() -> SfResult<()> {
47    let mut window = RenderWindow::new(
48        (800, 600),
49        "Custom shape",
50        Style::DEFAULT,
51        &Default::default(),
52    )?;
53    let clock = Clock::start()?;
54    window.set_vertical_sync_enabled(true);
55
56    let mut shape = CustomShape::new(Box::new(TriangleShape));
57    shape.set_position((400., 300.));
58    shape.set_origin((400., 300.));
59    shape.set_outline_thickness(3.);
60
61    'mainloop: loop {
62        while let Some(event) = window.poll_event() {
63            match event {
64                Event::Closed
65                | Event::KeyPressed {
66                    code: Key::Escape, ..
67                } => break 'mainloop,
68                _ => {}
69            }
70        }
71
72        let t = clock.elapsed_time().as_seconds();
73
74        shape.set_rotation(t.sin().abs() * 360.0);
75        let scale = t.cos().abs();
76        shape.set_scale(scale);
77        shape.set_fill_color(hue_time(t));
78        shape.set_outline_color(hue_time(t / 2.0));
79        window.clear(Color::BLACK);
80        window.draw(&shape);
81        window.display();
82    }
83    Ok(())
84}
examples/vertex-buffers.rs (lines 10-15)
9fn main() -> SfResult<()> {
10    let mut window = RenderWindow::new(
11        (800, 600),
12        "SFML VertexBuffer accessors Example",
13        Style::CLOSE,
14        &Default::default(),
15    )?;
16    window.set_vertical_sync_enabled(true);
17
18    let mut vertices = vec![
19        Vertex::with_pos_color((20.0, 30.0).into(), Color::GREEN),
20        Vertex::with_pos_color((30.0, 30.0).into(), Color::GREEN),
21        Vertex::with_pos_color((40.0, 40.0).into(), Color::GREEN),
22        Vertex::with_pos_color((50.0, 50.0).into(), Color::GREEN),
23        Vertex::with_pos_color((60.0, 60.0).into(), Color::GREEN),
24        Vertex::with_pos_color((50.0, 80.0).into(), Color::GREEN),
25    ];
26    let mut vertex_buffer = VertexBuffer::new(
27        PrimitiveType::LINE_STRIP,
28        vertices.len(),
29        VertexBufferUsage::DYNAMIC,
30    )?;
31    vertex_buffer.update(&vertices, 0)?;
32
33    'mainloop: loop {
34        while let Some(e) = window.poll_event() {
35            match e {
36                Event::Closed => break 'mainloop,
37                Event::MouseButtonPressed {
38                    button: Button::Left,
39                    x,
40                    y,
41                } => {
42                    vertices.push(Vertex::with_pos_color(
43                        (x as f32, y as f32).into(),
44                        Color::GREEN,
45                    ));
46                    vertex_buffer.update(&vertices, 0)?;
47                }
48                _ => {}
49            }
50        }
51        // Clear the window
52        window.clear(Color::BLACK);
53        window.draw(&*vertex_buffer);
54        // Display things on screen
55        window.display()
56    }
57    Ok(())
58}
examples/vertex-arrays.rs (lines 11-16)
10fn main() -> SfResult<()> {
11    let mut window = RenderWindow::new(
12        (800, 600),
13        "Vertex array example",
14        Style::CLOSE,
15        &Default::default(),
16    )?;
17    window.set_vertical_sync_enabled(true);
18
19    let mut vertex_array = [
20        Vertex::with_pos_color((20.0, 30.0).into(), Color::GREEN),
21        Vertex::with_pos_color((30.0, 30.0).into(), Color::GREEN),
22        Vertex::with_pos_color((40.0, 40.0).into(), Color::GREEN),
23        Vertex::with_pos_color((50.0, 50.0).into(), Color::GREEN),
24        Vertex::with_pos_color((60.0, 60.0).into(), Color::GREEN),
25        Vertex::with_pos_color((50.0, 80.0).into(), Color::GREEN),
26    ];
27
28    println!("\nIterate over the vertices of a vertex array");
29    for v in &vertex_array {
30        println!("Vertex Color: {:?} | Position: {:?}", v.color, v.position)
31    }
32
33    println!("\nMutable access to a vertex");
34    println!(
35        "Before Vertex Color: {:?} | Position: {:?}",
36        vertex_array[1].color, vertex_array[1].position
37    );
38    vertex_array[1].position.x = 100.0;
39    println!(
40        "After Vertex Color: {:?} | Position: {:?}",
41        vertex_array[1].color, vertex_array[1].position
42    );
43
44    println!("\nImmutable access to a vertex");
45    println!(
46        "Vertex Color: {:?} | Position: {:?}",
47        vertex_array[1].color, vertex_array[1].position
48    );
49
50    let vertex = &mut vertex_array[1];
51    println!(
52        "Before Vertex Color: {:?} | Position: {:?}",
53        vertex.color, vertex.position
54    );
55    vertex.position.x = 100.0;
56    println!(
57        "After Vertex Color: {:?} | Position: {:?}",
58        vertex.color, vertex.position
59    );
60
61    // Or:
62    vertex_array[1] = Vertex::with_pos((20., 40.).into());
63    println!("[2] After Vertex Position: {:?}", vertex_array[1].position);
64    println!(
65        "Vertex Color: {:?} | Position: {:?}",
66        vertex_array[1].color, vertex_array[1].position
67    );
68    let bounds = vertex_array_bounds(&vertex_array);
69    let mut bound_rect = RectangleShape::from_rect(bounds);
70    bound_rect.set_fill_color(Color::TRANSPARENT);
71    bound_rect.set_outline_thickness(1.0);
72    bound_rect.set_outline_color(Color::YELLOW);
73
74    'mainloop: loop {
75        while let Some(e) = window.poll_event() {
76            if e == Event::Closed {
77                break 'mainloop;
78            }
79        }
80        let rs = RenderStates::default();
81        // Clear the window
82        window.clear(Color::BLACK);
83        window.draw_primitives(&vertex_array, PrimitiveType::LINE_STRIP, &rs);
84        window.draw(&bound_rect);
85        // Display things on screen
86        window.display()
87    }
88    Ok(())
89}
examples/borrowed-resources.rs (lines 15-20)
12fn main() -> SfResult<()> {
13    example_ensure_right_working_dir();
14
15    let mut window = RenderWindow::new(
16        (800, 600),
17        "Borrowed resources",
18        Style::CLOSE,
19        &Default::default(),
20    )?;
21    window.set_vertical_sync_enabled(true);
22
23    // Create a new texture. (Hey Frank!)
24    let frank = Texture::from_file("frank.jpeg")?;
25
26    // Create a font.
27    let font = Font::from_file("sansation.ttf")?;
28
29    // Create a circle with the Texture.
30    let mut circle = CircleShape::with_texture(&frank);
31    circle.set_radius(70.0);
32    circle.set_position((100.0, 100.0));
33
34    // Create a Sprite.
35    let mut sprite = Sprite::new();
36    // Have it use the same texture as the circle.
37    sprite.set_texture(&frank, true);
38    sprite.set_position((400.0, 300.0));
39    sprite.set_scale(0.5);
40
41    // Create a ConvexShape using the same texture.
42    let mut convex_shape = ConvexShape::with_texture(6, &frank);
43    convex_shape.set_point(0, (400., 100.));
44    convex_shape.set_point(1, (500., 70.));
45    convex_shape.set_point(2, (450., 100.));
46    convex_shape.set_point(3, (580., 150.));
47    convex_shape.set_point(4, (420., 230.));
48    convex_shape.set_point(5, (420., 120.));
49
50    // Create an initialized text using the font.
51    let title = Text::new("Borrowed resources example!", &font, 50);
52
53    // Create a second text using the same font.
54    // This time, we create and initialize it separately.
55    let mut second_text = Text::default();
56    second_text.set_string("This text shares the same font with the title!");
57    second_text.set_font(&font);
58    second_text.set_fill_color(Color::GREEN);
59    second_text.set_position((10.0, 350.0));
60    second_text.set_character_size(20);
61
62    // Create a third text using the same font.
63    let mut third_text = Text::new("This one too!", &font, 20);
64    third_text.set_position((300.0, 100.0));
65    third_text.set_fill_color(Color::RED);
66
67    'mainloop: loop {
68        while let Some(event) = window.poll_event() {
69            match event {
70                Event::Closed
71                | Event::KeyPressed {
72                    code: Key::Escape, ..
73                } => break 'mainloop,
74                _ => {}
75            }
76        }
77
78        window.clear(Color::BLACK);
79        window.draw(&circle);
80        window.draw(&sprite);
81        window.draw(&convex_shape);
82        window.draw(&title);
83        window.draw(&second_text);
84        window.draw(&third_text);
85
86        // Little test here for `Shape::points`
87        let mut circ = CircleShape::new(4.0, 30);
88        circ.set_origin(2.0);
89        circ.set_fill_color(Color::YELLOW);
90
91        for p in convex_shape.points() {
92            circ.set_position(p);
93            window.draw(&circ);
94        }
95
96        window.display();
97    }
98    Ok(())
99}
Source

pub fn recreate<V: Into<VideoMode>, S: SfStrConv>( &mut self, mode: V, title: S, style: Style, settings: &ContextSettings, )

Recreate with new settings. See Self::new for more information.

Examples found in repository?
examples/window-test.rs (line 54)
13fn main() -> SfResult<()> {
14    let configs = [
15        WindowConfig {
16            mode: (320, 240),
17            title: "(Windowed) Retro",
18            style: Style::CLOSE,
19        },
20        WindowConfig {
21            mode: (640, 480),
22            title: "(Windowed) Classic",
23            style: Style::DEFAULT,
24        },
25        WindowConfig {
26            mode: (800, 600),
27            title: "(Windowed) Big",
28            style: Style::TITLEBAR,
29        },
30    ];
31    let mut cfg_idx = 2usize;
32    let mut rw = RenderWindow::new(
33        configs[cfg_idx].mode,
34        "Window test",
35        Style::CLOSE,
36        &ContextSettings::default(),
37    )?;
38    let font = Font::from_memory_static(include_bytes!("resources/sansation.ttf"))?;
39    let fs_modes = VideoMode::fullscreen_modes();
40
41    while rw.is_open() {
42        while let Some(ev) = rw.poll_event() {
43            match ev {
44                Event::Closed => rw.close(),
45                Event::KeyPressed { code, .. } => match code {
46                    Key::Up => cfg_idx = cfg_idx.saturating_sub(1),
47                    Key::Down => {
48                        if cfg_idx + 1 < configs.len() + fs_modes.len() {
49                            cfg_idx += 1
50                        }
51                    }
52                    Key::Enter => match configs.get(cfg_idx) {
53                        Some(cfg) => {
54                            rw.recreate(cfg.mode, cfg.title, cfg.style, &ContextSettings::default())
55                        }
56                        None => match fs_modes.get(cfg_idx - configs.len()) {
57                            Some(mode) => rw.recreate(
58                                *mode,
59                                "Fullscreen",
60                                Style::FULLSCREEN,
61                                &ContextSettings::default(),
62                            ),
63                            None => {
64                                eprintln!("Invalid index: {cfg_idx}");
65                            }
66                        },
67                    },
68                    _ => {}
69                },
70                _ => {}
71            }
72        }
73        rw.clear(Color::BLACK);
74        let fontsize = 16;
75        let mut txt = Text::new("Arrow keys to select mode, enter to set.", &font, fontsize);
76        rw.draw(&txt);
77        let mut y = fontsize as f32;
78        for (i, cfg) in configs.iter().enumerate() {
79            let fc = if i == cfg_idx {
80                Color::YELLOW
81            } else {
82                Color::WHITE
83            };
84            txt.set_fill_color(fc);
85            txt.set_string(&format!(
86                "{}x{} \"{}\" ({:?})",
87                cfg.mode.0, cfg.mode.1, cfg.title, cfg.style
88            ));
89            txt.set_position((0., y));
90            rw.draw(&txt);
91            y += fontsize as f32;
92        }
93        let mut i = configs.len();
94        y += fontsize as f32;
95        txt.set_position((0., y));
96        txt.set_fill_color(Color::WHITE);
97        txt.set_string("= Fullscreen modes =");
98        rw.draw(&txt);
99        for mode in fs_modes.iter() {
100            let n_rows = 23;
101            let column = i / n_rows;
102            let row = i % n_rows;
103            let fc = if i == cfg_idx {
104                Color::YELLOW
105            } else {
106                Color::WHITE
107            };
108            txt.set_fill_color(fc);
109            let left_pad = 16.0;
110            let x = left_pad + (column * 128) as f32;
111            let gap = 16.0;
112            let y = y + gap + (row * fontsize as usize) as f32;
113            txt.set_position((x, y));
114            txt.set_string(&format!(
115                "{}x{}x{}",
116                mode.width, mode.height, mode.bits_per_pixel
117            ));
118            rw.draw(&txt);
119            i += 1;
120        }
121        rw.display();
122    }
123    Ok(())
124}
Source

pub unsafe fn from_handle( handle: Handle, settings: &ContextSettings, ) -> SfResult<FBox<Self>>

Create a render window from an existing platform-specific window handle

This function creates a render window based on an existing platform specific window handle which has been allocated outside of SFML. This is only intended to be used in cases where you need to integrate SFML with some other windowing library.

§Safety

It is the caller’s responsibility to ensure that it is called with a valid window handle.

§Arguments
  • handle - The handle to the platform-specific window handle to use for the window.
  • settings - Additional settings for the underlying OpenGL context
Source§

impl RenderWindow

Event handling

Source

pub fn poll_event(&mut self) -> Option<Event>

Pop the event on top of event queue, if any, and return it

This function is not blocking: if there’s no pending event then it will return None. Note that more than one event may be present in the event queue, thus you should always call this function in a loop to make sure that you process every pending event.

Returns Some(event) if an event was returned, or None if the event queue was empty

Examples found in repository?
examples/custom-drawable.rs (line 53)
41fn main() -> SfResult<()> {
42    let mut window = RenderWindow::new(
43        (800, 600),
44        "Custom drawable",
45        Style::CLOSE,
46        &Default::default(),
47    )?;
48    window.set_vertical_sync_enabled(true);
49
50    let bullet = Bullet::new();
51
52    'mainloop: loop {
53        while let Some(event) = window.poll_event() {
54            match event {
55                Event::Closed
56                | Event::KeyPressed {
57                    code: Key::Escape, ..
58                } => break 'mainloop,
59                _ => {}
60            }
61        }
62
63        window.clear(Color::BLACK);
64        window.draw(&bullet);
65        window.display()
66    }
67    Ok(())
68}
More examples
Hide additional examples
examples/resource-holder.rs (line 72)
55fn main() -> SfResult<()> {
56    example_ensure_right_working_dir();
57
58    let mut tex_holder = ResourceHolder::<Texture, _>::default();
59    tex_holder.load("frank", "frank.jpeg")?;
60    let mut sb_holder = ResourceHolder::<SoundBuffer, _>::default();
61    sb_holder.load("canary", "canary.wav")?;
62    let mut rw = RenderWindow::new(
63        (800, 600),
64        "Resource holder test",
65        Style::CLOSE,
66        &Default::default(),
67    )?;
68    rw.set_vertical_sync_enabled(true);
69    let mut sound = Sound::with_buffer(sb_holder.get("canary"));
70    sound.play();
71    while rw.is_open() {
72        while let Some(ev) = rw.poll_event() {
73            match ev {
74                Event::Closed
75                | Event::KeyPressed {
76                    code: Key::Escape, ..
77                } => rw.close(),
78                _ => {}
79            }
80        }
81        rw.clear(Color::BLACK);
82        rw.draw(&Sprite::with_texture(tex_holder.get("frank")));
83        rw.display();
84    }
85    Ok(())
86}
examples/custom-shape.rs (line 62)
46fn main() -> SfResult<()> {
47    let mut window = RenderWindow::new(
48        (800, 600),
49        "Custom shape",
50        Style::DEFAULT,
51        &Default::default(),
52    )?;
53    let clock = Clock::start()?;
54    window.set_vertical_sync_enabled(true);
55
56    let mut shape = CustomShape::new(Box::new(TriangleShape));
57    shape.set_position((400., 300.));
58    shape.set_origin((400., 300.));
59    shape.set_outline_thickness(3.);
60
61    'mainloop: loop {
62        while let Some(event) = window.poll_event() {
63            match event {
64                Event::Closed
65                | Event::KeyPressed {
66                    code: Key::Escape, ..
67                } => break 'mainloop,
68                _ => {}
69            }
70        }
71
72        let t = clock.elapsed_time().as_seconds();
73
74        shape.set_rotation(t.sin().abs() * 360.0);
75        let scale = t.cos().abs();
76        shape.set_scale(scale);
77        shape.set_fill_color(hue_time(t));
78        shape.set_outline_color(hue_time(t / 2.0));
79        window.clear(Color::BLACK);
80        window.draw(&shape);
81        window.display();
82    }
83    Ok(())
84}
examples/vertex-buffers.rs (line 34)
9fn main() -> SfResult<()> {
10    let mut window = RenderWindow::new(
11        (800, 600),
12        "SFML VertexBuffer accessors Example",
13        Style::CLOSE,
14        &Default::default(),
15    )?;
16    window.set_vertical_sync_enabled(true);
17
18    let mut vertices = vec![
19        Vertex::with_pos_color((20.0, 30.0).into(), Color::GREEN),
20        Vertex::with_pos_color((30.0, 30.0).into(), Color::GREEN),
21        Vertex::with_pos_color((40.0, 40.0).into(), Color::GREEN),
22        Vertex::with_pos_color((50.0, 50.0).into(), Color::GREEN),
23        Vertex::with_pos_color((60.0, 60.0).into(), Color::GREEN),
24        Vertex::with_pos_color((50.0, 80.0).into(), Color::GREEN),
25    ];
26    let mut vertex_buffer = VertexBuffer::new(
27        PrimitiveType::LINE_STRIP,
28        vertices.len(),
29        VertexBufferUsage::DYNAMIC,
30    )?;
31    vertex_buffer.update(&vertices, 0)?;
32
33    'mainloop: loop {
34        while let Some(e) = window.poll_event() {
35            match e {
36                Event::Closed => break 'mainloop,
37                Event::MouseButtonPressed {
38                    button: Button::Left,
39                    x,
40                    y,
41                } => {
42                    vertices.push(Vertex::with_pos_color(
43                        (x as f32, y as f32).into(),
44                        Color::GREEN,
45                    ));
46                    vertex_buffer.update(&vertices, 0)?;
47                }
48                _ => {}
49            }
50        }
51        // Clear the window
52        window.clear(Color::BLACK);
53        window.draw(&*vertex_buffer);
54        // Display things on screen
55        window.display()
56    }
57    Ok(())
58}
examples/vertex-arrays.rs (line 75)
10fn main() -> SfResult<()> {
11    let mut window = RenderWindow::new(
12        (800, 600),
13        "Vertex array example",
14        Style::CLOSE,
15        &Default::default(),
16    )?;
17    window.set_vertical_sync_enabled(true);
18
19    let mut vertex_array = [
20        Vertex::with_pos_color((20.0, 30.0).into(), Color::GREEN),
21        Vertex::with_pos_color((30.0, 30.0).into(), Color::GREEN),
22        Vertex::with_pos_color((40.0, 40.0).into(), Color::GREEN),
23        Vertex::with_pos_color((50.0, 50.0).into(), Color::GREEN),
24        Vertex::with_pos_color((60.0, 60.0).into(), Color::GREEN),
25        Vertex::with_pos_color((50.0, 80.0).into(), Color::GREEN),
26    ];
27
28    println!("\nIterate over the vertices of a vertex array");
29    for v in &vertex_array {
30        println!("Vertex Color: {:?} | Position: {:?}", v.color, v.position)
31    }
32
33    println!("\nMutable access to a vertex");
34    println!(
35        "Before Vertex Color: {:?} | Position: {:?}",
36        vertex_array[1].color, vertex_array[1].position
37    );
38    vertex_array[1].position.x = 100.0;
39    println!(
40        "After Vertex Color: {:?} | Position: {:?}",
41        vertex_array[1].color, vertex_array[1].position
42    );
43
44    println!("\nImmutable access to a vertex");
45    println!(
46        "Vertex Color: {:?} | Position: {:?}",
47        vertex_array[1].color, vertex_array[1].position
48    );
49
50    let vertex = &mut vertex_array[1];
51    println!(
52        "Before Vertex Color: {:?} | Position: {:?}",
53        vertex.color, vertex.position
54    );
55    vertex.position.x = 100.0;
56    println!(
57        "After Vertex Color: {:?} | Position: {:?}",
58        vertex.color, vertex.position
59    );
60
61    // Or:
62    vertex_array[1] = Vertex::with_pos((20., 40.).into());
63    println!("[2] After Vertex Position: {:?}", vertex_array[1].position);
64    println!(
65        "Vertex Color: {:?} | Position: {:?}",
66        vertex_array[1].color, vertex_array[1].position
67    );
68    let bounds = vertex_array_bounds(&vertex_array);
69    let mut bound_rect = RectangleShape::from_rect(bounds);
70    bound_rect.set_fill_color(Color::TRANSPARENT);
71    bound_rect.set_outline_thickness(1.0);
72    bound_rect.set_outline_color(Color::YELLOW);
73
74    'mainloop: loop {
75        while let Some(e) = window.poll_event() {
76            if e == Event::Closed {
77                break 'mainloop;
78            }
79        }
80        let rs = RenderStates::default();
81        // Clear the window
82        window.clear(Color::BLACK);
83        window.draw_primitives(&vertex_array, PrimitiveType::LINE_STRIP, &rs);
84        window.draw(&bound_rect);
85        // Display things on screen
86        window.display()
87    }
88    Ok(())
89}
examples/borrowed-resources.rs (line 68)
12fn main() -> SfResult<()> {
13    example_ensure_right_working_dir();
14
15    let mut window = RenderWindow::new(
16        (800, 600),
17        "Borrowed resources",
18        Style::CLOSE,
19        &Default::default(),
20    )?;
21    window.set_vertical_sync_enabled(true);
22
23    // Create a new texture. (Hey Frank!)
24    let frank = Texture::from_file("frank.jpeg")?;
25
26    // Create a font.
27    let font = Font::from_file("sansation.ttf")?;
28
29    // Create a circle with the Texture.
30    let mut circle = CircleShape::with_texture(&frank);
31    circle.set_radius(70.0);
32    circle.set_position((100.0, 100.0));
33
34    // Create a Sprite.
35    let mut sprite = Sprite::new();
36    // Have it use the same texture as the circle.
37    sprite.set_texture(&frank, true);
38    sprite.set_position((400.0, 300.0));
39    sprite.set_scale(0.5);
40
41    // Create a ConvexShape using the same texture.
42    let mut convex_shape = ConvexShape::with_texture(6, &frank);
43    convex_shape.set_point(0, (400., 100.));
44    convex_shape.set_point(1, (500., 70.));
45    convex_shape.set_point(2, (450., 100.));
46    convex_shape.set_point(3, (580., 150.));
47    convex_shape.set_point(4, (420., 230.));
48    convex_shape.set_point(5, (420., 120.));
49
50    // Create an initialized text using the font.
51    let title = Text::new("Borrowed resources example!", &font, 50);
52
53    // Create a second text using the same font.
54    // This time, we create and initialize it separately.
55    let mut second_text = Text::default();
56    second_text.set_string("This text shares the same font with the title!");
57    second_text.set_font(&font);
58    second_text.set_fill_color(Color::GREEN);
59    second_text.set_position((10.0, 350.0));
60    second_text.set_character_size(20);
61
62    // Create a third text using the same font.
63    let mut third_text = Text::new("This one too!", &font, 20);
64    third_text.set_position((300.0, 100.0));
65    third_text.set_fill_color(Color::RED);
66
67    'mainloop: loop {
68        while let Some(event) = window.poll_event() {
69            match event {
70                Event::Closed
71                | Event::KeyPressed {
72                    code: Key::Escape, ..
73                } => break 'mainloop,
74                _ => {}
75            }
76        }
77
78        window.clear(Color::BLACK);
79        window.draw(&circle);
80        window.draw(&sprite);
81        window.draw(&convex_shape);
82        window.draw(&title);
83        window.draw(&second_text);
84        window.draw(&third_text);
85
86        // Little test here for `Shape::points`
87        let mut circ = CircleShape::new(4.0, 30);
88        circ.set_origin(2.0);
89        circ.set_fill_color(Color::YELLOW);
90
91        for p in convex_shape.points() {
92            circ.set_position(p);
93            window.draw(&circ);
94        }
95
96        window.display();
97    }
98    Ok(())
99}
Source

pub fn wait_event(&mut self) -> Option<Event>

Wait for an event and return it

This function is blocking: if there’s no pending event then it will wait until an event is received.

This function is typically used when you have a thread that is dedicated to events handling: you want to make this thread sleep as long as no new event is received.

Returns Some(event) or None if an error has occured

Source§

impl RenderWindow

Rendering. See also RenderTarget, which RenderWindow implements.

Source

pub fn display(&mut self)

Display on screen what has been rendered to the window so far

This function is typically called after all OpenGL rendering has been done for the current frame, in order to show it on screen.

Examples found in repository?
examples/custom-drawable.rs (line 65)
41fn main() -> SfResult<()> {
42    let mut window = RenderWindow::new(
43        (800, 600),
44        "Custom drawable",
45        Style::CLOSE,
46        &Default::default(),
47    )?;
48    window.set_vertical_sync_enabled(true);
49
50    let bullet = Bullet::new();
51
52    'mainloop: loop {
53        while let Some(event) = window.poll_event() {
54            match event {
55                Event::Closed
56                | Event::KeyPressed {
57                    code: Key::Escape, ..
58                } => break 'mainloop,
59                _ => {}
60            }
61        }
62
63        window.clear(Color::BLACK);
64        window.draw(&bullet);
65        window.display()
66    }
67    Ok(())
68}
More examples
Hide additional examples
examples/resource-holder.rs (line 83)
55fn main() -> SfResult<()> {
56    example_ensure_right_working_dir();
57
58    let mut tex_holder = ResourceHolder::<Texture, _>::default();
59    tex_holder.load("frank", "frank.jpeg")?;
60    let mut sb_holder = ResourceHolder::<SoundBuffer, _>::default();
61    sb_holder.load("canary", "canary.wav")?;
62    let mut rw = RenderWindow::new(
63        (800, 600),
64        "Resource holder test",
65        Style::CLOSE,
66        &Default::default(),
67    )?;
68    rw.set_vertical_sync_enabled(true);
69    let mut sound = Sound::with_buffer(sb_holder.get("canary"));
70    sound.play();
71    while rw.is_open() {
72        while let Some(ev) = rw.poll_event() {
73            match ev {
74                Event::Closed
75                | Event::KeyPressed {
76                    code: Key::Escape, ..
77                } => rw.close(),
78                _ => {}
79            }
80        }
81        rw.clear(Color::BLACK);
82        rw.draw(&Sprite::with_texture(tex_holder.get("frank")));
83        rw.display();
84    }
85    Ok(())
86}
examples/custom-shape.rs (line 81)
46fn main() -> SfResult<()> {
47    let mut window = RenderWindow::new(
48        (800, 600),
49        "Custom shape",
50        Style::DEFAULT,
51        &Default::default(),
52    )?;
53    let clock = Clock::start()?;
54    window.set_vertical_sync_enabled(true);
55
56    let mut shape = CustomShape::new(Box::new(TriangleShape));
57    shape.set_position((400., 300.));
58    shape.set_origin((400., 300.));
59    shape.set_outline_thickness(3.);
60
61    'mainloop: loop {
62        while let Some(event) = window.poll_event() {
63            match event {
64                Event::Closed
65                | Event::KeyPressed {
66                    code: Key::Escape, ..
67                } => break 'mainloop,
68                _ => {}
69            }
70        }
71
72        let t = clock.elapsed_time().as_seconds();
73
74        shape.set_rotation(t.sin().abs() * 360.0);
75        let scale = t.cos().abs();
76        shape.set_scale(scale);
77        shape.set_fill_color(hue_time(t));
78        shape.set_outline_color(hue_time(t / 2.0));
79        window.clear(Color::BLACK);
80        window.draw(&shape);
81        window.display();
82    }
83    Ok(())
84}
examples/vertex-buffers.rs (line 55)
9fn main() -> SfResult<()> {
10    let mut window = RenderWindow::new(
11        (800, 600),
12        "SFML VertexBuffer accessors Example",
13        Style::CLOSE,
14        &Default::default(),
15    )?;
16    window.set_vertical_sync_enabled(true);
17
18    let mut vertices = vec![
19        Vertex::with_pos_color((20.0, 30.0).into(), Color::GREEN),
20        Vertex::with_pos_color((30.0, 30.0).into(), Color::GREEN),
21        Vertex::with_pos_color((40.0, 40.0).into(), Color::GREEN),
22        Vertex::with_pos_color((50.0, 50.0).into(), Color::GREEN),
23        Vertex::with_pos_color((60.0, 60.0).into(), Color::GREEN),
24        Vertex::with_pos_color((50.0, 80.0).into(), Color::GREEN),
25    ];
26    let mut vertex_buffer = VertexBuffer::new(
27        PrimitiveType::LINE_STRIP,
28        vertices.len(),
29        VertexBufferUsage::DYNAMIC,
30    )?;
31    vertex_buffer.update(&vertices, 0)?;
32
33    'mainloop: loop {
34        while let Some(e) = window.poll_event() {
35            match e {
36                Event::Closed => break 'mainloop,
37                Event::MouseButtonPressed {
38                    button: Button::Left,
39                    x,
40                    y,
41                } => {
42                    vertices.push(Vertex::with_pos_color(
43                        (x as f32, y as f32).into(),
44                        Color::GREEN,
45                    ));
46                    vertex_buffer.update(&vertices, 0)?;
47                }
48                _ => {}
49            }
50        }
51        // Clear the window
52        window.clear(Color::BLACK);
53        window.draw(&*vertex_buffer);
54        // Display things on screen
55        window.display()
56    }
57    Ok(())
58}
examples/vertex-arrays.rs (line 86)
10fn main() -> SfResult<()> {
11    let mut window = RenderWindow::new(
12        (800, 600),
13        "Vertex array example",
14        Style::CLOSE,
15        &Default::default(),
16    )?;
17    window.set_vertical_sync_enabled(true);
18
19    let mut vertex_array = [
20        Vertex::with_pos_color((20.0, 30.0).into(), Color::GREEN),
21        Vertex::with_pos_color((30.0, 30.0).into(), Color::GREEN),
22        Vertex::with_pos_color((40.0, 40.0).into(), Color::GREEN),
23        Vertex::with_pos_color((50.0, 50.0).into(), Color::GREEN),
24        Vertex::with_pos_color((60.0, 60.0).into(), Color::GREEN),
25        Vertex::with_pos_color((50.0, 80.0).into(), Color::GREEN),
26    ];
27
28    println!("\nIterate over the vertices of a vertex array");
29    for v in &vertex_array {
30        println!("Vertex Color: {:?} | Position: {:?}", v.color, v.position)
31    }
32
33    println!("\nMutable access to a vertex");
34    println!(
35        "Before Vertex Color: {:?} | Position: {:?}",
36        vertex_array[1].color, vertex_array[1].position
37    );
38    vertex_array[1].position.x = 100.0;
39    println!(
40        "After Vertex Color: {:?} | Position: {:?}",
41        vertex_array[1].color, vertex_array[1].position
42    );
43
44    println!("\nImmutable access to a vertex");
45    println!(
46        "Vertex Color: {:?} | Position: {:?}",
47        vertex_array[1].color, vertex_array[1].position
48    );
49
50    let vertex = &mut vertex_array[1];
51    println!(
52        "Before Vertex Color: {:?} | Position: {:?}",
53        vertex.color, vertex.position
54    );
55    vertex.position.x = 100.0;
56    println!(
57        "After Vertex Color: {:?} | Position: {:?}",
58        vertex.color, vertex.position
59    );
60
61    // Or:
62    vertex_array[1] = Vertex::with_pos((20., 40.).into());
63    println!("[2] After Vertex Position: {:?}", vertex_array[1].position);
64    println!(
65        "Vertex Color: {:?} | Position: {:?}",
66        vertex_array[1].color, vertex_array[1].position
67    );
68    let bounds = vertex_array_bounds(&vertex_array);
69    let mut bound_rect = RectangleShape::from_rect(bounds);
70    bound_rect.set_fill_color(Color::TRANSPARENT);
71    bound_rect.set_outline_thickness(1.0);
72    bound_rect.set_outline_color(Color::YELLOW);
73
74    'mainloop: loop {
75        while let Some(e) = window.poll_event() {
76            if e == Event::Closed {
77                break 'mainloop;
78            }
79        }
80        let rs = RenderStates::default();
81        // Clear the window
82        window.clear(Color::BLACK);
83        window.draw_primitives(&vertex_array, PrimitiveType::LINE_STRIP, &rs);
84        window.draw(&bound_rect);
85        // Display things on screen
86        window.display()
87    }
88    Ok(())
89}
examples/borrowed-resources.rs (line 96)
12fn main() -> SfResult<()> {
13    example_ensure_right_working_dir();
14
15    let mut window = RenderWindow::new(
16        (800, 600),
17        "Borrowed resources",
18        Style::CLOSE,
19        &Default::default(),
20    )?;
21    window.set_vertical_sync_enabled(true);
22
23    // Create a new texture. (Hey Frank!)
24    let frank = Texture::from_file("frank.jpeg")?;
25
26    // Create a font.
27    let font = Font::from_file("sansation.ttf")?;
28
29    // Create a circle with the Texture.
30    let mut circle = CircleShape::with_texture(&frank);
31    circle.set_radius(70.0);
32    circle.set_position((100.0, 100.0));
33
34    // Create a Sprite.
35    let mut sprite = Sprite::new();
36    // Have it use the same texture as the circle.
37    sprite.set_texture(&frank, true);
38    sprite.set_position((400.0, 300.0));
39    sprite.set_scale(0.5);
40
41    // Create a ConvexShape using the same texture.
42    let mut convex_shape = ConvexShape::with_texture(6, &frank);
43    convex_shape.set_point(0, (400., 100.));
44    convex_shape.set_point(1, (500., 70.));
45    convex_shape.set_point(2, (450., 100.));
46    convex_shape.set_point(3, (580., 150.));
47    convex_shape.set_point(4, (420., 230.));
48    convex_shape.set_point(5, (420., 120.));
49
50    // Create an initialized text using the font.
51    let title = Text::new("Borrowed resources example!", &font, 50);
52
53    // Create a second text using the same font.
54    // This time, we create and initialize it separately.
55    let mut second_text = Text::default();
56    second_text.set_string("This text shares the same font with the title!");
57    second_text.set_font(&font);
58    second_text.set_fill_color(Color::GREEN);
59    second_text.set_position((10.0, 350.0));
60    second_text.set_character_size(20);
61
62    // Create a third text using the same font.
63    let mut third_text = Text::new("This one too!", &font, 20);
64    third_text.set_position((300.0, 100.0));
65    third_text.set_fill_color(Color::RED);
66
67    'mainloop: loop {
68        while let Some(event) = window.poll_event() {
69            match event {
70                Event::Closed
71                | Event::KeyPressed {
72                    code: Key::Escape, ..
73                } => break 'mainloop,
74                _ => {}
75            }
76        }
77
78        window.clear(Color::BLACK);
79        window.draw(&circle);
80        window.draw(&sprite);
81        window.draw(&convex_shape);
82        window.draw(&title);
83        window.draw(&second_text);
84        window.draw(&third_text);
85
86        // Little test here for `Shape::points`
87        let mut circ = CircleShape::new(4.0, 30);
88        circ.set_origin(2.0);
89        circ.set_fill_color(Color::YELLOW);
90
91        for p in convex_shape.points() {
92            circ.set_position(p);
93            window.draw(&circ);
94        }
95
96        window.display();
97    }
98    Ok(())
99}
Source

pub fn set_framerate_limit(&mut self, limit: u32)

Limit the framerate to a maximum fixed frequency

If a limit is set, the window will use a small delay after each call to RenderWindow::display to ensure that the current frame lasted long enough to match the framerate limit.

§Arguments
  • limit - Framerate limit, in frames per seconds (use 0 to disable limit)
Examples found in repository?
examples/rc-resources.rs (line 126)
121fn main() -> SfResult<()> {
122    example_ensure_right_working_dir();
123
124    let mut window =
125        RenderWindow::new((800, 600), "SFML window", Style::CLOSE, &Default::default())?;
126    window.set_framerate_limit(60);
127
128    // Create a new texture.
129    let texture = RcTexture::from_file("logo.png")?;
130    let texture2 = test_getting_rc_texture_from_texture()?;
131
132    // Create a new font.
133    let font_path = match std::env::args().nth(1) {
134        Some(path) => path,
135        None => "sansation.ttf".into(),
136    };
137    let mut font = RcFont::from_file(&font_path)?;
138
139    // Load many resources with no lifetime contingencies
140    let mut floating_resources = Vec::from([
141        FloatingResource::with_texture(&texture2, true, true, 1.1f32),
142        FloatingResource::with_texture(&texture2, true, true, 1.2f32),
143        FloatingResource::with_texture(&texture, true, true, 1f32),
144        FloatingResource::with_texture(&texture, true, false, 1.5f32),
145        FloatingResource::with_texture(&texture, false, true, 2f32),
146        FloatingResource::with_texture(&texture, false, false, 2.5f32),
147        FloatingResource::with_font(&font, true, true, 1.25f32),
148        FloatingResource::with_font(&font, true, true, 1.75f32),
149        FloatingResource::with_font(&font, true, true, 2.25f32),
150        FloatingResource::with_font(&font, true, true, 2.75f32),
151    ]);
152
153    let set_smooth_text = get_set_smooth_rc_text(&font);
154    let mut show_texture_atlas = false;
155    let mut text_buf = String::from("SFML");
156
157    while window.is_open() {
158        while let Some(event) = window.poll_event() {
159            if event == Event::Closed {
160                window.close();
161            }
162
163            match event {
164                Event::Closed => window.close(),
165                Event::KeyPressed { code, ctrl, .. } => match code {
166                    Key::S => {
167                        let smooth = !font.is_smooth();
168                        font.set_smooth(smooth);
169                    }
170                    Key::T => {
171                        show_texture_atlas ^= true;
172                    }
173                    Key::V if ctrl => {
174                        text_buf.push_str(&clipboard::get_string());
175                    }
176                    _ => {}
177                },
178                Event::TextEntered { unicode } if show_texture_atlas => {
179                    if unicode == 0x8 as char {
180                        text_buf.pop();
181                    } else if !unicode.is_ascii_control() && unicode != 's' && unicode != 't' {
182                        text_buf.push(unicode);
183                    }
184                }
185                _ => {}
186            }
187        }
188
189        // Update floating_resource positions so they move around on the screen
190        for floating_resource in &mut floating_resources {
191            floating_resource.move_resources(Vector2f::new(800f32, 600f32));
192            floating_resource.text.set_string(&text_buf);
193        }
194
195        window.clear(Color::BLACK);
196
197        // Fetch and draw all the sprites in floating_resources
198        for floating_resource in &floating_resources {
199            floating_resource.render(&mut window);
200        }
201
202        window.draw(&set_smooth_text);
203        if show_texture_atlas {
204            let scale = 3.0;
205            let tex = font.texture(16);
206            let mut rs = RectangleShape::with_size(tex.size().as_other());
207            rs.set_fill_color(Color::MAGENTA);
208            rs.set_scale(scale);
209            window.draw(&rs);
210            let mut s = Sprite::with_texture(&*tex);
211            s.set_scale(scale);
212            window.draw(&s);
213        }
214        window.display();
215    }
216    Ok(())
217}
Source

pub fn settings(&self) -> &ContextSettings

Get the settings of the OpenGL context of a window

Note that these settings may be different from what was passed to the RenderWindow::new function, if one or more settings were not supported. In this case, SFML chose the closest match.

Return a structure containing the OpenGL context settings

Examples found in repository?
examples/pong.rs (line 53)
21fn main() -> SfResult<()> {
22    example_ensure_right_working_dir();
23
24    let mut rng = thread_rng();
25
26    // Optional antialiasing
27    let mut aa_level = 0;
28
29    if let Some(arg) = env::args().nth(1) {
30        match arg.parse::<u32>() {
31            Ok(arg_as_num) => aa_level = arg_as_num,
32            Err(e) => println!("Didn't set AA level: {e}"),
33        }
34    }
35
36    // Define some constants
37    let game_width = 800;
38    let game_height = 600;
39    let paddle_size = Vector2f::new(25., 100.);
40    let ball_radius = 10.;
41
42    // Create the window of the application
43    let context_settings = ContextSettings {
44        antialiasing_level: aa_level,
45        ..Default::default()
46    };
47    let mut window = RenderWindow::new(
48        (game_width, game_height),
49        "SFML Pong",
50        Style::CLOSE,
51        &context_settings,
52    )?;
53    let context_settings = window.settings();
54    if context_settings.antialiasing_level > 0 {
55        println!("Using {}xAA", context_settings.antialiasing_level);
56    }
57    window.set_vertical_sync_enabled(true);
58
59    // Load the sounds used in the game
60    let ball_soundbuffer = SoundBuffer::from_file("ball.wav")?;
61    let mut ball_sound = Sound::with_buffer(&ball_soundbuffer);
62
63    // Create the left paddle
64    let mut left_paddle = RectangleShape::new();
65    left_paddle.set_size(paddle_size - Vector2f::new(3., 3.));
66    left_paddle.set_outline_thickness(3.);
67    left_paddle.set_outline_color(Color::BLACK);
68    left_paddle.set_fill_color(Color::rgb(100, 100, 200));
69    left_paddle.set_origin(paddle_size / 2.);
70
71    // Create the right paddle
72    let mut right_paddle = RectangleShape::new();
73    right_paddle.set_size(paddle_size - Vector2f::new(3., 3.));
74    right_paddle.set_outline_thickness(3.);
75    right_paddle.set_outline_color(Color::BLACK);
76    right_paddle.set_fill_color(Color::rgb(200, 100, 100));
77    right_paddle.set_origin(paddle_size / 2.);
78
79    // Create the ball
80    let mut ball = CircleShape::default();
81    ball.set_radius(ball_radius - 3.);
82    ball.set_outline_thickness(3.);
83    ball.set_outline_color(Color::BLACK);
84    ball.set_fill_color(Color::WHITE);
85    ball.set_origin(ball_radius / 2.);
86
87    // Load the text font
88    let font = Font::from_file("sansation.ttf")?;
89
90    // Initialize the pause message
91    let mut pause_message = Text::default();
92    pause_message.set_font(&font);
93    pause_message.set_character_size(40);
94    pause_message.set_position((170., 150.));
95    pause_message.set_fill_color(Color::WHITE);
96    pause_message.set_string("Welcome to SFML pong!\nPress space to start the game");
97
98    // Define the paddles properties
99    let mut ai_timer = Clock::start()?;
100    let paddle_speed = 400.;
101    let mut right_paddle_speed = 0.;
102    let mut ball_speed = 400.;
103    let mut ball_angle = 0.;
104
105    let mut clock = Clock::start()?;
106    let mut is_playing = false;
107    let mut up = false;
108    let mut down = false;
109
110    'mainloop: loop {
111        while let Some(event) = window.poll_event() {
112            match event {
113                Event::Closed
114                | Event::KeyPressed {
115                    code: Key::Escape, ..
116                } => break 'mainloop,
117                Event::KeyPressed {
118                    code: Key::Space, ..
119                } if !is_playing => {
120                    // (re)start the game
121                    is_playing = true;
122                    ball_speed = 400.0;
123                    ball_sound.set_pitch(1.0);
124                    clock.restart();
125                    // Reset the position of the paddles and ball
126                    left_paddle.set_position((10. + paddle_size.x / 2., game_height as f32 / 2.));
127                    right_paddle.set_position((
128                        game_width as f32 - 10. - paddle_size.x / 2.,
129                        game_height as f32 / 2.,
130                    ));
131                    ball.set_position((game_width as f32 / 2., game_height as f32 / 2.));
132                    // Reset the ball angle
133                    loop {
134                        // Make sure the ball initial angle is not too much vertical
135                        ball_angle = rng.gen_range(0.0..360.) * 2. * PI / 360.;
136
137                        if ball_angle.cos().abs() >= 0.7 {
138                            break;
139                        }
140                    }
141                }
142                Event::KeyPressed { code: Key::Up, .. }
143                | Event::KeyPressed {
144                    scan: Scancode::W, ..
145                } => up = true,
146                Event::KeyReleased { code: Key::Up, .. }
147                | Event::KeyReleased {
148                    scan: Scancode::W, ..
149                } => up = false,
150                Event::KeyPressed {
151                    code: Key::Down, ..
152                }
153                | Event::KeyPressed {
154                    scan: Scancode::S, ..
155                } => down = true,
156                Event::KeyReleased {
157                    code: Key::Down, ..
158                }
159                | Event::KeyReleased {
160                    scan: Scancode::S, ..
161                } => down = false,
162                _ => {}
163            }
164        }
165        if is_playing {
166            let delta_time = clock.restart().as_seconds();
167
168            // Move the player's paddle
169            if up && (left_paddle.position().y - paddle_size.y / 2. > 5.) {
170                left_paddle.move_((0., -paddle_speed * delta_time));
171            }
172            if down && (left_paddle.position().y + paddle_size.y / 2. < game_height as f32 - 5.) {
173                left_paddle.move_((0., paddle_speed * delta_time));
174            }
175
176            // Move the computer's paddle
177            if ((right_paddle_speed < 0.) && (right_paddle.position().y - paddle_size.y / 2. > 5.))
178                || ((right_paddle_speed > 0.)
179                    && (right_paddle.position().y + paddle_size.y / 2. < game_height as f32 - 5.))
180            {
181                right_paddle.move_((0., right_paddle_speed * delta_time));
182            }
183
184            // Update the computer's paddle direction according to the ball position
185            if ai_timer.elapsed_time() > AI_REACT_DELAY {
186                ai_timer.restart();
187                if ball.position().y + ball_radius > right_paddle.position().y + paddle_size.y / 2.
188                {
189                    right_paddle_speed = paddle_speed;
190                } else if ball.position().y - ball_radius
191                    < right_paddle.position().y - paddle_size.y / 2.
192                {
193                    right_paddle_speed = -paddle_speed;
194                } else {
195                    right_paddle_speed = 0.;
196                }
197            }
198
199            // Move the ball
200            let factor = ball_speed * delta_time;
201            ball.move_((ball_angle.cos() * factor, ball_angle.sin() * factor));
202
203            // Check collisions between the ball and the screen
204            if ball.position().x - ball_radius < 0. {
205                is_playing = false;
206                pause_message.set_string("You lost !\nPress space to restart or\nescape to exit");
207            }
208            if ball.position().x + ball_radius > game_width as f32 {
209                is_playing = false;
210                pause_message.set_string("You won !\nPress space to restart or\nescape to exit");
211            }
212            if ball.position().y - ball_radius < 0. {
213                on_bounce(&mut ball_sound, &mut ball_speed);
214                ball_angle = -ball_angle;
215                let p = ball.position().x;
216                ball.set_position((p, ball_radius + 0.1));
217            }
218            if ball.position().y + ball_radius > game_height as f32 {
219                on_bounce(&mut ball_sound, &mut ball_speed);
220                ball_angle = -ball_angle;
221                let p = ball.position().x;
222                ball.set_position((p, game_height as f32 - ball_radius - 0.1));
223            }
224
225            // Check the collisions between the ball and the paddles
226            // Left Paddle
227            let (ball_pos, paddle_pos) = (ball.position(), left_paddle.position());
228            if ball_pos.x - ball_radius < paddle_pos.x + paddle_size.x / 2.
229                && ball_pos.y + ball_radius >= paddle_pos.y - paddle_size.y / 2.
230                && ball_pos.y - ball_radius <= paddle_pos.y + paddle_size.y / 2.
231            {
232                if ball_pos.y > paddle_pos.y {
233                    ball_angle = PI - ball_angle + rng.gen_range(0.0..20.) * PI / 180.;
234                } else {
235                    ball_angle = PI - ball_angle - rng.gen_range(0.0..20.) * PI / 180.;
236                }
237
238                on_bounce(&mut ball_sound, &mut ball_speed);
239                ball.set_position((
240                    paddle_pos.x + ball_radius + paddle_size.x / 2. + 0.1,
241                    ball_pos.y,
242                ));
243            }
244
245            // Right Paddle
246            let (ball_pos, paddle_pos) = (ball.position(), right_paddle.position());
247            if ball_pos.x + ball_radius > paddle_pos.x - paddle_size.x / 2.
248                && ball_pos.y + ball_radius >= paddle_pos.y - paddle_size.y / 2.
249                && ball_pos.y - ball_radius <= paddle_pos.y + paddle_size.y / 2.
250            {
251                if ball_pos.y > paddle_pos.y {
252                    ball_angle = PI - ball_angle + rng.gen_range(0.0..20.) * PI / 180.;
253                } else {
254                    ball_angle = PI - ball_angle - rng.gen_range(0.0..20.) * PI / 180.;
255                }
256
257                on_bounce(&mut ball_sound, &mut ball_speed);
258                ball.set_position((
259                    paddle_pos.x - ball_radius - paddle_size.x / 2. - 0.1,
260                    ball_pos.y,
261                ));
262            }
263        }
264        // Clear the window
265        window.clear(Color::rgb(50, 200, 50));
266
267        if is_playing {
268            // Draw the paddles and the ball
269            window.draw(&left_paddle);
270            window.draw(&right_paddle);
271            window.draw(&ball);
272        } else {
273            // Draw the pause message
274            window.draw(&pause_message);
275        }
276
277        // Display things on screen
278        window.display()
279    }
280    Ok(())
281}
Source

pub fn is_srgb(&self) -> bool

Tell if the render texture will use sRGB encoding when drawing it

Returns true if sRGB encoding is enabled, false if sRGB encoding is disabled

Source

pub fn set_vertical_sync_enabled(&mut self, enabled: bool)

Enable or disable vertical synchronization

Activating vertical synchronization will limit the number of frames displayed to the refresh rate of the monitor. This can avoid some visual artifacts, and limit the framerate to a good value (but not constant across different computers).

§Arguments
  • enabled - true to enable v-sync, false to deactivate
Examples found in repository?
examples/custom-drawable.rs (line 48)
41fn main() -> SfResult<()> {
42    let mut window = RenderWindow::new(
43        (800, 600),
44        "Custom drawable",
45        Style::CLOSE,
46        &Default::default(),
47    )?;
48    window.set_vertical_sync_enabled(true);
49
50    let bullet = Bullet::new();
51
52    'mainloop: loop {
53        while let Some(event) = window.poll_event() {
54            match event {
55                Event::Closed
56                | Event::KeyPressed {
57                    code: Key::Escape, ..
58                } => break 'mainloop,
59                _ => {}
60            }
61        }
62
63        window.clear(Color::BLACK);
64        window.draw(&bullet);
65        window.display()
66    }
67    Ok(())
68}
More examples
Hide additional examples
examples/resource-holder.rs (line 68)
55fn main() -> SfResult<()> {
56    example_ensure_right_working_dir();
57
58    let mut tex_holder = ResourceHolder::<Texture, _>::default();
59    tex_holder.load("frank", "frank.jpeg")?;
60    let mut sb_holder = ResourceHolder::<SoundBuffer, _>::default();
61    sb_holder.load("canary", "canary.wav")?;
62    let mut rw = RenderWindow::new(
63        (800, 600),
64        "Resource holder test",
65        Style::CLOSE,
66        &Default::default(),
67    )?;
68    rw.set_vertical_sync_enabled(true);
69    let mut sound = Sound::with_buffer(sb_holder.get("canary"));
70    sound.play();
71    while rw.is_open() {
72        while let Some(ev) = rw.poll_event() {
73            match ev {
74                Event::Closed
75                | Event::KeyPressed {
76                    code: Key::Escape, ..
77                } => rw.close(),
78                _ => {}
79            }
80        }
81        rw.clear(Color::BLACK);
82        rw.draw(&Sprite::with_texture(tex_holder.get("frank")));
83        rw.display();
84    }
85    Ok(())
86}
examples/custom-shape.rs (line 54)
46fn main() -> SfResult<()> {
47    let mut window = RenderWindow::new(
48        (800, 600),
49        "Custom shape",
50        Style::DEFAULT,
51        &Default::default(),
52    )?;
53    let clock = Clock::start()?;
54    window.set_vertical_sync_enabled(true);
55
56    let mut shape = CustomShape::new(Box::new(TriangleShape));
57    shape.set_position((400., 300.));
58    shape.set_origin((400., 300.));
59    shape.set_outline_thickness(3.);
60
61    'mainloop: loop {
62        while let Some(event) = window.poll_event() {
63            match event {
64                Event::Closed
65                | Event::KeyPressed {
66                    code: Key::Escape, ..
67                } => break 'mainloop,
68                _ => {}
69            }
70        }
71
72        let t = clock.elapsed_time().as_seconds();
73
74        shape.set_rotation(t.sin().abs() * 360.0);
75        let scale = t.cos().abs();
76        shape.set_scale(scale);
77        shape.set_fill_color(hue_time(t));
78        shape.set_outline_color(hue_time(t / 2.0));
79        window.clear(Color::BLACK);
80        window.draw(&shape);
81        window.display();
82    }
83    Ok(())
84}
examples/vertex-buffers.rs (line 16)
9fn main() -> SfResult<()> {
10    let mut window = RenderWindow::new(
11        (800, 600),
12        "SFML VertexBuffer accessors Example",
13        Style::CLOSE,
14        &Default::default(),
15    )?;
16    window.set_vertical_sync_enabled(true);
17
18    let mut vertices = vec![
19        Vertex::with_pos_color((20.0, 30.0).into(), Color::GREEN),
20        Vertex::with_pos_color((30.0, 30.0).into(), Color::GREEN),
21        Vertex::with_pos_color((40.0, 40.0).into(), Color::GREEN),
22        Vertex::with_pos_color((50.0, 50.0).into(), Color::GREEN),
23        Vertex::with_pos_color((60.0, 60.0).into(), Color::GREEN),
24        Vertex::with_pos_color((50.0, 80.0).into(), Color::GREEN),
25    ];
26    let mut vertex_buffer = VertexBuffer::new(
27        PrimitiveType::LINE_STRIP,
28        vertices.len(),
29        VertexBufferUsage::DYNAMIC,
30    )?;
31    vertex_buffer.update(&vertices, 0)?;
32
33    'mainloop: loop {
34        while let Some(e) = window.poll_event() {
35            match e {
36                Event::Closed => break 'mainloop,
37                Event::MouseButtonPressed {
38                    button: Button::Left,
39                    x,
40                    y,
41                } => {
42                    vertices.push(Vertex::with_pos_color(
43                        (x as f32, y as f32).into(),
44                        Color::GREEN,
45                    ));
46                    vertex_buffer.update(&vertices, 0)?;
47                }
48                _ => {}
49            }
50        }
51        // Clear the window
52        window.clear(Color::BLACK);
53        window.draw(&*vertex_buffer);
54        // Display things on screen
55        window.display()
56    }
57    Ok(())
58}
examples/vertex-arrays.rs (line 17)
10fn main() -> SfResult<()> {
11    let mut window = RenderWindow::new(
12        (800, 600),
13        "Vertex array example",
14        Style::CLOSE,
15        &Default::default(),
16    )?;
17    window.set_vertical_sync_enabled(true);
18
19    let mut vertex_array = [
20        Vertex::with_pos_color((20.0, 30.0).into(), Color::GREEN),
21        Vertex::with_pos_color((30.0, 30.0).into(), Color::GREEN),
22        Vertex::with_pos_color((40.0, 40.0).into(), Color::GREEN),
23        Vertex::with_pos_color((50.0, 50.0).into(), Color::GREEN),
24        Vertex::with_pos_color((60.0, 60.0).into(), Color::GREEN),
25        Vertex::with_pos_color((50.0, 80.0).into(), Color::GREEN),
26    ];
27
28    println!("\nIterate over the vertices of a vertex array");
29    for v in &vertex_array {
30        println!("Vertex Color: {:?} | Position: {:?}", v.color, v.position)
31    }
32
33    println!("\nMutable access to a vertex");
34    println!(
35        "Before Vertex Color: {:?} | Position: {:?}",
36        vertex_array[1].color, vertex_array[1].position
37    );
38    vertex_array[1].position.x = 100.0;
39    println!(
40        "After Vertex Color: {:?} | Position: {:?}",
41        vertex_array[1].color, vertex_array[1].position
42    );
43
44    println!("\nImmutable access to a vertex");
45    println!(
46        "Vertex Color: {:?} | Position: {:?}",
47        vertex_array[1].color, vertex_array[1].position
48    );
49
50    let vertex = &mut vertex_array[1];
51    println!(
52        "Before Vertex Color: {:?} | Position: {:?}",
53        vertex.color, vertex.position
54    );
55    vertex.position.x = 100.0;
56    println!(
57        "After Vertex Color: {:?} | Position: {:?}",
58        vertex.color, vertex.position
59    );
60
61    // Or:
62    vertex_array[1] = Vertex::with_pos((20., 40.).into());
63    println!("[2] After Vertex Position: {:?}", vertex_array[1].position);
64    println!(
65        "Vertex Color: {:?} | Position: {:?}",
66        vertex_array[1].color, vertex_array[1].position
67    );
68    let bounds = vertex_array_bounds(&vertex_array);
69    let mut bound_rect = RectangleShape::from_rect(bounds);
70    bound_rect.set_fill_color(Color::TRANSPARENT);
71    bound_rect.set_outline_thickness(1.0);
72    bound_rect.set_outline_color(Color::YELLOW);
73
74    'mainloop: loop {
75        while let Some(e) = window.poll_event() {
76            if e == Event::Closed {
77                break 'mainloop;
78            }
79        }
80        let rs = RenderStates::default();
81        // Clear the window
82        window.clear(Color::BLACK);
83        window.draw_primitives(&vertex_array, PrimitiveType::LINE_STRIP, &rs);
84        window.draw(&bound_rect);
85        // Display things on screen
86        window.display()
87    }
88    Ok(())
89}
examples/borrowed-resources.rs (line 21)
12fn main() -> SfResult<()> {
13    example_ensure_right_working_dir();
14
15    let mut window = RenderWindow::new(
16        (800, 600),
17        "Borrowed resources",
18        Style::CLOSE,
19        &Default::default(),
20    )?;
21    window.set_vertical_sync_enabled(true);
22
23    // Create a new texture. (Hey Frank!)
24    let frank = Texture::from_file("frank.jpeg")?;
25
26    // Create a font.
27    let font = Font::from_file("sansation.ttf")?;
28
29    // Create a circle with the Texture.
30    let mut circle = CircleShape::with_texture(&frank);
31    circle.set_radius(70.0);
32    circle.set_position((100.0, 100.0));
33
34    // Create a Sprite.
35    let mut sprite = Sprite::new();
36    // Have it use the same texture as the circle.
37    sprite.set_texture(&frank, true);
38    sprite.set_position((400.0, 300.0));
39    sprite.set_scale(0.5);
40
41    // Create a ConvexShape using the same texture.
42    let mut convex_shape = ConvexShape::with_texture(6, &frank);
43    convex_shape.set_point(0, (400., 100.));
44    convex_shape.set_point(1, (500., 70.));
45    convex_shape.set_point(2, (450., 100.));
46    convex_shape.set_point(3, (580., 150.));
47    convex_shape.set_point(4, (420., 230.));
48    convex_shape.set_point(5, (420., 120.));
49
50    // Create an initialized text using the font.
51    let title = Text::new("Borrowed resources example!", &font, 50);
52
53    // Create a second text using the same font.
54    // This time, we create and initialize it separately.
55    let mut second_text = Text::default();
56    second_text.set_string("This text shares the same font with the title!");
57    second_text.set_font(&font);
58    second_text.set_fill_color(Color::GREEN);
59    second_text.set_position((10.0, 350.0));
60    second_text.set_character_size(20);
61
62    // Create a third text using the same font.
63    let mut third_text = Text::new("This one too!", &font, 20);
64    third_text.set_position((300.0, 100.0));
65    third_text.set_fill_color(Color::RED);
66
67    'mainloop: loop {
68        while let Some(event) = window.poll_event() {
69            match event {
70                Event::Closed
71                | Event::KeyPressed {
72                    code: Key::Escape, ..
73                } => break 'mainloop,
74                _ => {}
75            }
76        }
77
78        window.clear(Color::BLACK);
79        window.draw(&circle);
80        window.draw(&sprite);
81        window.draw(&convex_shape);
82        window.draw(&title);
83        window.draw(&second_text);
84        window.draw(&third_text);
85
86        // Little test here for `Shape::points`
87        let mut circ = CircleShape::new(4.0, 30);
88        circ.set_origin(2.0);
89        circ.set_fill_color(Color::YELLOW);
90
91        for p in convex_shape.points() {
92            circ.set_position(p);
93            window.draw(&circ);
94        }
95
96        window.display();
97    }
98    Ok(())
99}
Source

pub fn set_active(&mut self, enabled: bool) -> SfResult<()>

Activate or deactivate a render window as the current target for OpenGL rendering

A window is active only on the current thread, if you want to make it active on another thread you have to deactivate it on the previous thread first if it was active. Only one window can be active on a thread at a time, thus the window previously active (if any) automatically gets deactivated.

§Arguments
  • active - true to activate, false to deactivate
Examples found in repository?
examples/opengl.rs (line 55)
16fn main() -> SfResult<()> {
17    example_ensure_right_working_dir();
18
19    let mut exit = false;
20    let mut srgb = false;
21
22    while !exit {
23        let ctx_sett = ContextSettings {
24            depth_bits: 24,
25            srgb_capable: srgb,
26            ..Default::default()
27        };
28
29        let mut window = RenderWindow::new(
30            (800, 600),
31            "SFML graphics with OpenGL",
32            Style::default(),
33            &ctx_sett,
34        )?;
35        window.set_vertical_sync_enabled(true);
36
37        let mut bg_tex = Texture::new()?;
38        bg_tex.set_srgb(srgb);
39        bg_tex.load_from_file("opengl-background.jpg", IntRect::default())?;
40        let bg_sprite = Sprite::with_texture(&bg_tex);
41
42        let font = Font::from_file("sansation.ttf")?;
43        let mut text = Text::new("SFML / OpenGL demo", &font, 32);
44        let mut srgb_instr = Text::new("Press space to toggle sRGB conversion", &font, 32);
45        let mut mipmap_instr = Text::new("Press return to toggle mipmapping", &font, 32);
46        text.set_fill_color(Color::rgba(255, 255, 255, 170));
47        srgb_instr.set_fill_color(Color::rgba(255, 255, 255, 170));
48        mipmap_instr.set_fill_color(Color::rgba(255, 255, 255, 170));
49        text.set_position((250., 450.));
50        srgb_instr.set_position((150., 500.));
51        mipmap_instr.set_position((180., 550.));
52
53        let mut texture = Texture::from_file("texture.jpg")?;
54        texture.generate_mipmap()?;
55        window.set_active(true)?;
56        unsafe {
57            gl::glEnable(gl::GL_DEPTH_TEST);
58            gl::glDepthMask(gl::GL_TRUE as _);
59            gl::glClearDepth(1.);
60            gl::glDisable(gl::GL_LIGHTING);
61            gl::glViewport(0, 0, window.size().x as _, window.size().y as _);
62            gl::glMatrixMode(gl::GL_PROJECTION);
63            gl::glLoadIdentity();
64            let ratio = (window.size().x / window.size().y) as gl::GLdouble;
65            gl::glFrustum(-ratio, ratio, -1., 1., 1., 500.);
66            gl::glEnable(gl::GL_TEXTURE_2D);
67            Texture::bind(&texture);
68        }
69
70        let cube: [f32; 180] = [
71            -20., -20., -20., 0., 0., -20., 20., -20., 1., 0., -20., -20., 20., 0., 1., -20., -20.,
72            20., 0., 1., -20., 20., -20., 1., 0., -20., 20., 20., 1., 1., 20., -20., -20., 0., 0.,
73            20., 20., -20., 1., 0., 20., -20., 20., 0., 1., 20., -20., 20., 0., 1., 20., 20., -20.,
74            1., 0., 20., 20., 20., 1., 1., -20., -20., -20., 0., 0., 20., -20., -20., 1., 0., -20.,
75            -20., 20., 0., 1., -20., -20., 20., 0., 1., 20., -20., -20., 1., 0., 20., -20., 20.,
76            1., 1., -20., 20., -20., 0., 0., 20., 20., -20., 1., 0., -20., 20., 20., 0., 1., -20.,
77            20., 20., 0., 1., 20., 20., -20., 1., 0., 20., 20., 20., 1., 1., -20., -20., -20., 0.,
78            0., 20., -20., -20., 1., 0., -20., 20., -20., 0., 1., -20., 20., -20., 0., 1., 20.,
79            -20., -20., 1., 0., 20., 20., -20., 1., 1., -20., -20., 20., 0., 0., 20., -20., 20.,
80            1., 0., -20., 20., 20., 0., 1., -20., 20., 20., 0., 1., 20., -20., 20., 1., 0., 20.,
81            20., 20., 1., 1.,
82        ];
83
84        unsafe {
85            gl::glEnableClientState(gl::GL_VERTEX_ARRAY);
86            gl::glEnableClientState(gl::GL_TEXTURE_COORD_ARRAY);
87            gl::glVertexPointer(
88                3,
89                gl::GL_FLOAT,
90                5 * size_of::<gl::GLfloat>() as i32,
91                cube.as_ptr() as *const c_void,
92            );
93            gl::glTexCoordPointer(
94                2,
95                gl::GL_FLOAT,
96                5 * size_of::<gl::GLfloat>() as i32,
97                cube.as_ptr().offset(3) as *const c_void,
98            );
99
100            // Disable normal and color vertex components
101            gl::glDisableClientState(gl::GL_NORMAL_ARRAY);
102            gl::glDisableClientState(gl::GL_COLOR_ARRAY);
103        }
104
105        window.set_active(false)?;
106        let clock = Clock::start()?;
107        let mut mipmap_enabled = true;
108
109        while window.is_open() {
110            while let Some(event) = window.poll_event() {
111                match event {
112                    Event::Closed
113                    | Event::KeyPressed {
114                        code: Key::Escape, ..
115                    } => {
116                        exit = true;
117                        window.close();
118                    }
119                    Event::KeyPressed {
120                        code: Key::Enter, ..
121                    } => {
122                        if mipmap_enabled {
123                            texture = Texture::from_file("texture.jpg")?;
124                            mipmap_enabled = false;
125                            window.set_active(true)?;
126                            Texture::bind(&texture);
127                            window.set_active(false)?;
128                        } else {
129                            texture.generate_mipmap()?;
130                            mipmap_enabled = true;
131                        }
132                    }
133                    Event::KeyPressed {
134                        code: Key::Space, ..
135                    } => {
136                        srgb = !srgb;
137                        window.close();
138                    }
139                    Event::Resized { width, height } => {
140                        window.set_active(true)?;
141                        unsafe {
142                            gl::glViewport(0, 0, width as _, height as _);
143                        }
144                        window.set_active(false)?;
145                    }
146                    _ => {}
147                }
148            }
149            window.push_gl_states();
150            window.draw(&bg_sprite);
151            window.pop_gl_states();
152
153            if let Err(e) = window.set_active(true) {
154                eprintln!("Failed to set window as active: {e}");
155            }
156
157            unsafe {
158                gl::glClear(gl::GL_DEPTH_BUFFER_BIT);
159                let x: f32 =
160                    window.mouse_position().x as f32 * 200. / window.size().x as f32 - 100.;
161                let y: f32 =
162                    -window.mouse_position().y as f32 * 200. / window.size().y as f32 + 100.;
163
164                gl::glMatrixMode(gl::GL_MODELVIEW);
165                gl::glLoadIdentity();
166                gl::glTranslatef(x, y, -100.);
167                gl::glRotatef(clock.elapsed_time().as_seconds() * 50., 1., 0., 0.);
168                gl::glRotatef(clock.elapsed_time().as_seconds() * 30., 0., 1., 0.);
169                gl::glRotatef(clock.elapsed_time().as_seconds() * 90., 0., 0., 1.);
170                gl::glDrawArrays(gl::GL_TRIANGLES, 0, 36);
171            }
172            if let Err(e) = window.set_active(false) {
173                eprintln!("Failed to set window as active: {e}");
174            }
175            window.push_gl_states();
176            window.draw(&text);
177            window.draw(&srgb_instr);
178            window.draw(&mipmap_instr);
179            window.pop_gl_states();
180            window.display();
181        }
182    }
183    Ok(())
184}
Source§

impl RenderWindow

Input

Source

pub fn set_mouse_cursor_visible(&mut self, visible: bool)

Show or hide the mouse cursor

§Arguments
  • visible - true to false to hide
Examples found in repository?
examples/mouse.rs (line 14)
5fn main() -> SfResult<()> {
6    example_ensure_right_working_dir();
7
8    let mut window = RenderWindow::new(
9        (800, 600),
10        "Mouse events",
11        Style::CLOSE,
12        &Default::default(),
13    )?;
14    window.set_mouse_cursor_visible(false);
15    window.set_vertical_sync_enabled(true);
16
17    let font = Font::from_file("sansation.ttf")?;
18    let mut circle = CircleShape::new(4., 30);
19    let mut texts: Vec<Text> = Vec::new();
20    let mut mp_text = Text::new("", &font, 14);
21    let mut cursor_visible = false;
22    let mut grabbed = false;
23    macro_rules! push_text {
24        ($x:expr, $y:expr, $fmt:expr, $($arg:tt)*) => {
25            let mut text = Text::new(&format!($fmt, $($arg)*), &font, 14);
26            text.set_position(($x as f32, $y as f32));
27            texts.push(text);
28        }
29    }
30
31    'mainloop: loop {
32        while let Some(ev) = window.poll_event() {
33            match ev {
34                Event::Closed => break 'mainloop,
35                Event::MouseWheelScrolled { wheel, delta, x, y } => {
36                    push_text!(x, y, "Scroll: {:?}, {}, {}, {}", wheel, delta, x, y);
37                }
38                Event::MouseButtonPressed { button, x, y } => {
39                    push_text!(x, y, "Press: {:?}, {}, {}", button, x, y);
40                }
41                Event::MouseButtonReleased { button, x, y } => {
42                    push_text!(x, y, "Release: {:?}, {}, {}", button, x, y);
43                }
44                Event::KeyPressed { code, .. } => {
45                    if code == Key::W {
46                        window.set_mouse_position(Vector2i::new(400, 300));
47                    } else if code == Key::D {
48                        let dm = VideoMode::desktop_mode();
49                        let center = Vector2i::new(dm.width as i32 / 2, dm.height as i32 / 2);
50                        mouse::set_desktop_position(center);
51                    } else if code == Key::V {
52                        cursor_visible = !cursor_visible;
53                        window.set_mouse_cursor_visible(cursor_visible);
54                    } else if code == Key::G {
55                        grabbed = !grabbed;
56                        window.set_mouse_cursor_grabbed(grabbed);
57                    }
58                }
59                _ => {}
60            }
61        }
62
63        let mp = window.mouse_position();
64        let dmp = mouse::desktop_position();
65        let cur_vis_msg = if cursor_visible {
66            "visible"
67        } else {
68            "invisible"
69        };
70        let grab_msg = if grabbed { "grabbed" } else { "not grabbed" };
71        mp_text.set_string(&format!(
72            "x: {}, y: {} (Window)\n\
73             x: {}, y: {} (Desktop)\n\
74             [{cur_vis_msg}] [{grab_msg}] ('V'/'G') to toggle\n\
75             'W' to center mouse on window\n\
76             'D' to center mouse on desktop",
77            mp.x, mp.y, dmp.x, dmp.y
78        ));
79
80        circle.set_position((mp.x as f32, mp.y as f32));
81
82        window.clear(Color::BLACK);
83        // Push texts out of each other's way
84        for i in (0..texts.len()).rev() {
85            for j in (0..i).rev() {
86                if let Some(intersect) = texts[i]
87                    .global_bounds()
88                    .intersection(&texts[j].global_bounds())
89                {
90                    texts[j].move_((0., -intersect.height));
91                }
92            }
93        }
94        texts.retain(|txt| txt.fill_color().a > 0);
95        for txt in &mut texts {
96            let mut color = txt.fill_color();
97            color.a -= 1;
98            txt.set_fill_color(color);
99            window.draw(txt);
100        }
101        if !cursor_visible {
102            window.draw(&circle);
103        }
104        window.draw(&mp_text);
105        window.display();
106    }
107    Ok(())
108}
Source

pub fn set_mouse_cursor_grabbed(&mut self, grabbed: bool)

Grab or release the mouse cursor.

If set, grabs the mouse cursor inside this window’s client area so it may no longer be moved outside its bounds. Note that grabbing is only active while the window has focus.

Examples found in repository?
examples/mouse.rs (line 56)
5fn main() -> SfResult<()> {
6    example_ensure_right_working_dir();
7
8    let mut window = RenderWindow::new(
9        (800, 600),
10        "Mouse events",
11        Style::CLOSE,
12        &Default::default(),
13    )?;
14    window.set_mouse_cursor_visible(false);
15    window.set_vertical_sync_enabled(true);
16
17    let font = Font::from_file("sansation.ttf")?;
18    let mut circle = CircleShape::new(4., 30);
19    let mut texts: Vec<Text> = Vec::new();
20    let mut mp_text = Text::new("", &font, 14);
21    let mut cursor_visible = false;
22    let mut grabbed = false;
23    macro_rules! push_text {
24        ($x:expr, $y:expr, $fmt:expr, $($arg:tt)*) => {
25            let mut text = Text::new(&format!($fmt, $($arg)*), &font, 14);
26            text.set_position(($x as f32, $y as f32));
27            texts.push(text);
28        }
29    }
30
31    'mainloop: loop {
32        while let Some(ev) = window.poll_event() {
33            match ev {
34                Event::Closed => break 'mainloop,
35                Event::MouseWheelScrolled { wheel, delta, x, y } => {
36                    push_text!(x, y, "Scroll: {:?}, {}, {}, {}", wheel, delta, x, y);
37                }
38                Event::MouseButtonPressed { button, x, y } => {
39                    push_text!(x, y, "Press: {:?}, {}, {}", button, x, y);
40                }
41                Event::MouseButtonReleased { button, x, y } => {
42                    push_text!(x, y, "Release: {:?}, {}, {}", button, x, y);
43                }
44                Event::KeyPressed { code, .. } => {
45                    if code == Key::W {
46                        window.set_mouse_position(Vector2i::new(400, 300));
47                    } else if code == Key::D {
48                        let dm = VideoMode::desktop_mode();
49                        let center = Vector2i::new(dm.width as i32 / 2, dm.height as i32 / 2);
50                        mouse::set_desktop_position(center);
51                    } else if code == Key::V {
52                        cursor_visible = !cursor_visible;
53                        window.set_mouse_cursor_visible(cursor_visible);
54                    } else if code == Key::G {
55                        grabbed = !grabbed;
56                        window.set_mouse_cursor_grabbed(grabbed);
57                    }
58                }
59                _ => {}
60            }
61        }
62
63        let mp = window.mouse_position();
64        let dmp = mouse::desktop_position();
65        let cur_vis_msg = if cursor_visible {
66            "visible"
67        } else {
68            "invisible"
69        };
70        let grab_msg = if grabbed { "grabbed" } else { "not grabbed" };
71        mp_text.set_string(&format!(
72            "x: {}, y: {} (Window)\n\
73             x: {}, y: {} (Desktop)\n\
74             [{cur_vis_msg}] [{grab_msg}] ('V'/'G') to toggle\n\
75             'W' to center mouse on window\n\
76             'D' to center mouse on desktop",
77            mp.x, mp.y, dmp.x, dmp.y
78        ));
79
80        circle.set_position((mp.x as f32, mp.y as f32));
81
82        window.clear(Color::BLACK);
83        // Push texts out of each other's way
84        for i in (0..texts.len()).rev() {
85            for j in (0..i).rev() {
86                if let Some(intersect) = texts[i]
87                    .global_bounds()
88                    .intersection(&texts[j].global_bounds())
89                {
90                    texts[j].move_((0., -intersect.height));
91                }
92            }
93        }
94        texts.retain(|txt| txt.fill_color().a > 0);
95        for txt in &mut texts {
96            let mut color = txt.fill_color();
97            color.a -= 1;
98            txt.set_fill_color(color);
99            window.draw(txt);
100        }
101        if !cursor_visible {
102            window.draw(&circle);
103        }
104        window.draw(&mp_text);
105        window.display();
106    }
107    Ok(())
108}
Source

pub fn set_key_repeat_enabled(&mut self, enabled: bool)

Enable or disable automatic key-repeat

If key repeat is enabled, you will receive repeated crate::window::Event::KeyPressed events while keeping a key pressed. If it is disabled, you will only get a single event when the key is pressed.

Key repeat is enabled by default.

§Arguments
  • enabled - true to enable, false to disable
Source

pub fn set_joystick_threshold(&mut self, threshold: f32)

Change the joystick threshold

The joystick threshold is the value below which no crate::window::Event::JoystickMoved event will be generated.

§Arguments
  • threshold - New threshold, in the range [0, 100]
Source

pub fn mouse_position(&self) -> Vector2i

Returns the current position of the mouse relative to the window.

Examples found in repository?
examples/shader.rs (line 324)
258fn main() -> SfResult<()> {
259    example_ensure_right_working_dir();
260
261    let mut window = RenderWindow::new(
262        (800, 600),
263        "SFML Shader",
264        Style::TITLEBAR | Style::CLOSE,
265        &Default::default(),
266    )?;
267    window.set_vertical_sync_enabled(true);
268    let font = Font::from_file("sansation.ttf")?;
269    let bg = Texture::from_file("background.jpg")?;
270    let mut bg_texture = Texture::from_file("sfml.png")?;
271    bg_texture.set_smooth(true);
272    let mut entity_texture = Texture::from_file("devices.png")?;
273    entity_texture.set_smooth(true);
274    let effects: [&mut dyn Effect; 4] = [
275        &mut Pixelate::new(&bg)?,
276        &mut WaveBlur::new(&font)?,
277        &mut StormBlink::new()?,
278        &mut Edge::new(&bg_texture, &entity_texture)?,
279    ];
280    let mut current = 0;
281    let text_bg_texture = Texture::from_file("text-background.png")?;
282    let mut text_bg = Sprite::with_texture(&text_bg_texture);
283    text_bg.set_position((0., 520.));
284    text_bg.set_color(Color::rgba(255, 255, 255, 200));
285    let msg = format!("Current effect: {}", effects[current].name());
286    let mut desc = Text::new(&msg, &font, 20);
287    desc.set_position((10., 530.));
288    desc.set_fill_color(Color::rgb(80, 80, 80));
289    let msg = "Press left and right arrows to change the current shader";
290    let mut instructions = Text::new(msg, &font, 20);
291    instructions.set_position((280., 555.));
292    instructions.set_fill_color(Color::rgb(80, 80, 80));
293    let clock = Clock::start()?;
294
295    while window.is_open() {
296        while let Some(event) = window.poll_event() {
297            use crate::Event::*;
298            match event {
299                Closed => window.close(),
300                KeyPressed { code, .. } => match code {
301                    Key::Escape => window.close(),
302                    Key::Left => {
303                        if current == 0 {
304                            current = effects.len() - 1;
305                        } else {
306                            current -= 1;
307                        }
308                        desc.set_string(&format!("Current effect: {}", effects[current].name()));
309                    }
310                    Key::Right => {
311                        if current == effects.len() - 1 {
312                            current = 0;
313                        } else {
314                            current += 1;
315                        }
316                        desc.set_string(&format!("Current effect: {}", effects[current].name()));
317                    }
318                    _ => {}
319                },
320                _ => {}
321            }
322        }
323
324        let x = window.mouse_position().x as f32 / window.size().x as f32;
325        let y = window.mouse_position().y as f32 / window.size().y as f32;
326
327        effects[current].update(clock.elapsed_time().as_seconds(), x, y)?;
328
329        window.clear(Color::rgb(255, 128, 0));
330        window.draw(effects[current].as_drawable());
331        window.draw(&text_bg);
332        window.draw(&instructions);
333        window.draw(&desc);
334        window.display();
335    }
336    Ok(())
337}
More examples
Hide additional examples
examples/mouse.rs (line 63)
5fn main() -> SfResult<()> {
6    example_ensure_right_working_dir();
7
8    let mut window = RenderWindow::new(
9        (800, 600),
10        "Mouse events",
11        Style::CLOSE,
12        &Default::default(),
13    )?;
14    window.set_mouse_cursor_visible(false);
15    window.set_vertical_sync_enabled(true);
16
17    let font = Font::from_file("sansation.ttf")?;
18    let mut circle = CircleShape::new(4., 30);
19    let mut texts: Vec<Text> = Vec::new();
20    let mut mp_text = Text::new("", &font, 14);
21    let mut cursor_visible = false;
22    let mut grabbed = false;
23    macro_rules! push_text {
24        ($x:expr, $y:expr, $fmt:expr, $($arg:tt)*) => {
25            let mut text = Text::new(&format!($fmt, $($arg)*), &font, 14);
26            text.set_position(($x as f32, $y as f32));
27            texts.push(text);
28        }
29    }
30
31    'mainloop: loop {
32        while let Some(ev) = window.poll_event() {
33            match ev {
34                Event::Closed => break 'mainloop,
35                Event::MouseWheelScrolled { wheel, delta, x, y } => {
36                    push_text!(x, y, "Scroll: {:?}, {}, {}, {}", wheel, delta, x, y);
37                }
38                Event::MouseButtonPressed { button, x, y } => {
39                    push_text!(x, y, "Press: {:?}, {}, {}", button, x, y);
40                }
41                Event::MouseButtonReleased { button, x, y } => {
42                    push_text!(x, y, "Release: {:?}, {}, {}", button, x, y);
43                }
44                Event::KeyPressed { code, .. } => {
45                    if code == Key::W {
46                        window.set_mouse_position(Vector2i::new(400, 300));
47                    } else if code == Key::D {
48                        let dm = VideoMode::desktop_mode();
49                        let center = Vector2i::new(dm.width as i32 / 2, dm.height as i32 / 2);
50                        mouse::set_desktop_position(center);
51                    } else if code == Key::V {
52                        cursor_visible = !cursor_visible;
53                        window.set_mouse_cursor_visible(cursor_visible);
54                    } else if code == Key::G {
55                        grabbed = !grabbed;
56                        window.set_mouse_cursor_grabbed(grabbed);
57                    }
58                }
59                _ => {}
60            }
61        }
62
63        let mp = window.mouse_position();
64        let dmp = mouse::desktop_position();
65        let cur_vis_msg = if cursor_visible {
66            "visible"
67        } else {
68            "invisible"
69        };
70        let grab_msg = if grabbed { "grabbed" } else { "not grabbed" };
71        mp_text.set_string(&format!(
72            "x: {}, y: {} (Window)\n\
73             x: {}, y: {} (Desktop)\n\
74             [{cur_vis_msg}] [{grab_msg}] ('V'/'G') to toggle\n\
75             'W' to center mouse on window\n\
76             'D' to center mouse on desktop",
77            mp.x, mp.y, dmp.x, dmp.y
78        ));
79
80        circle.set_position((mp.x as f32, mp.y as f32));
81
82        window.clear(Color::BLACK);
83        // Push texts out of each other's way
84        for i in (0..texts.len()).rev() {
85            for j in (0..i).rev() {
86                if let Some(intersect) = texts[i]
87                    .global_bounds()
88                    .intersection(&texts[j].global_bounds())
89                {
90                    texts[j].move_((0., -intersect.height));
91                }
92            }
93        }
94        texts.retain(|txt| txt.fill_color().a > 0);
95        for txt in &mut texts {
96            let mut color = txt.fill_color();
97            color.a -= 1;
98            txt.set_fill_color(color);
99            window.draw(txt);
100        }
101        if !cursor_visible {
102            window.draw(&circle);
103        }
104        window.draw(&mp_text);
105        window.display();
106    }
107    Ok(())
108}
examples/positional-audio.rs (line 95)
46fn main() -> Result<(), Box<dyn Error>> {
47    example_ensure_right_working_dir();
48
49    let mut rw = RenderWindow::new(
50        (800, 600),
51        "Positional audio demo",
52        Style::CLOSE,
53        &Default::default(),
54    )?;
55    rw.set_vertical_sync_enabled(true);
56    let font = Font::from_file("sansation.ttf")?;
57    let mut text = Text::new("", &font, 20);
58    let mut music = match std::env::args().nth(1) {
59        Some(music_path) => Music::from_file(&music_path)?,
60        None => Music::from_file("canary.wav")?,
61    };
62    if music.channel_count() != 1 {
63        return Err("Sorry, only sounds with 1 channel are supported.".into());
64    };
65    music.set_looping(true);
66    music.play();
67    music.set_position(Vector3::new(0., 0., 0.));
68
69    let mut listener_pos = Vector3::new(0.0, 0.0, 0.0);
70    let center = Vector2::new(400., 300.);
71    let [mut go_left, mut go_right, mut go_up, mut go_down] = [false; 4];
72    let clock = Clock::start()?;
73
74    while rw.is_open() {
75        while let Some(ev) = rw.poll_event() {
76            match ev {
77                Event::Closed => rw.close(),
78                Event::KeyPressed { code, .. } => match code {
79                    Key::A => go_left = true,
80                    Key::D => go_right = true,
81                    Key::W => go_up = true,
82                    Key::S => go_down = true,
83                    _ => {}
84                },
85                Event::KeyReleased { code, .. } => match code {
86                    Key::A => go_left = false,
87                    Key::D => go_right = false,
88                    Key::W => go_up = false,
89                    Key::S => go_down = false,
90                    _ => {}
91                },
92                _ => {}
93            }
94        }
95        let Vector2f { x: mx, y: my } = rw.mouse_position().as_other();
96        let speed = 0.05;
97        if go_left {
98            listener_pos.x -= speed;
99        }
100        if go_right {
101            listener_pos.x += speed;
102        }
103        if go_up {
104            listener_pos.y -= speed;
105        }
106        if go_down {
107            listener_pos.y += speed;
108        }
109        let scale = 20.0; // Scale the positions for better visualization
110        listener::set_position(listener_pos);
111        listener::set_direction(Vector3::new(
112            (mx - center.x) / scale,
113            (my - center.y) / scale,
114            -1.,
115        ));
116        let Vector3 {
117            x: lx,
118            y: ly,
119            z: lz,
120        } = listener::position();
121        let Vector3 {
122            x: dx,
123            y: dy,
124            z: dz,
125        } = listener::direction();
126        rw.clear(Color::BLACK);
127        let mut circle_shape = CircleShape::new(8.0, 32);
128        // Draw circle at center, representing position of music being played
129        circle_shape.set_position(center);
130        circle_shape.set_fill_color(Color::YELLOW);
131        let t = clock.elapsed_time().as_seconds();
132        let radius = 12.0 + t.sin() * 3.0;
133        circle_shape.set_radius(radius);
134        circle_shape.set_origin(radius);
135        rw.draw(&circle_shape);
136        // Draw circle representing listener
137        circle_shape.set_position((center.x + lx * scale, center.y + ly * scale));
138        circle_shape.set_origin(4.0);
139        circle_shape.set_radius(4.0);
140        circle_shape.set_fill_color(Color::GREEN);
141        rw.draw(&circle_shape);
142        // Draw line from listener to direction vector position
143        rw.draw_line(
144            circle_shape.position(),
145            (center.x + dx * scale, center.y + dy * scale).into(),
146            2.0,
147        );
148        text.set_string("WASD + mouse for movement of listener");
149        text.set_position(0.);
150        rw.draw(&text);
151        text.set_string(&format!("Listener position: {lx}, {ly}, {lz}"));
152        text.set_position((0., 20.0));
153        rw.draw(&text);
154        text.set_string(&format!("Listener direction: {dx}, {dy}, {dz}"));
155        text.set_position((0., 40.0));
156        rw.draw(&text);
157        rw.display();
158    }
159    Ok(())
160}
examples/spritemark.rs (line 119)
62fn main() -> SfResult<()> {
63    example_ensure_right_working_dir();
64
65    let native_mode = VideoMode::desktop_mode();
66    let mut window = RenderWindow::new(
67        native_mode,
68        "Spritemark",
69        Style::default(),
70        &ContextSettings::default(),
71    )?;
72    window.set_position(Vector2::new(0, 0));
73    window.set_vertical_sync_enabled(true);
74    let font = Font::from_file("sansation.ttf")?;
75    let texture = Texture::from_file("devices.png")?;
76    let mut text = Text::new("", &font, 18);
77    text.set_outline_color(Color::BLACK);
78    text.set_outline_thickness(1.0);
79    let mut click_counter = 0;
80    let mut objects = Vec::new();
81    let mut rng = thread_rng();
82    let mut rs = RenderStates::default();
83    let mut buf = Vec::new();
84    let mut frames_rendered = 0;
85    let mut sec_clock = Clock::start()?;
86    let mut fps = 0;
87    let mut lmb_down = false;
88    let mut view = View::new()?;
89
90    while window.is_open() {
91        while let Some(event) = window.poll_event() {
92            match event {
93                Event::Closed
94                | Event::KeyPressed {
95                    code: Key::Escape, ..
96                } => window.close(),
97                Event::MouseButtonPressed {
98                    button: Button::Left,
99                    ..
100                } => {
101                    click_counter += 1;
102                    lmb_down = true;
103                }
104                Event::MouseButtonReleased {
105                    button: Button::Left,
106                    ..
107                } => {
108                    lmb_down = false;
109                }
110                Event::Resized { width, height } => {
111                    view.reset(Rect::new(0., 0., width as f32, height as f32));
112                    window.set_view(&view);
113                }
114                _ => {}
115            }
116        }
117
118        if lmb_down {
119            let mp = window.mouse_position();
120            for _ in 0..25 {
121                objects.push(Object {
122                    position: fconv(mp),
123                    speed: Vector2f::new(rng.gen_range(-3.0..3.0), 0.0),
124                    image_id: click_counter % N_IMAGES,
125                    angle: 0.0,
126                    rot_speed: rng.gen_range(-2.0..2.0),
127                });
128            }
129        }
130
131        for obj in &mut objects {
132            let size = f32::from(SUBIMAGE_SIZE);
133            let tex_x = f32::from(obj.image_id) * size;
134            let mut tf = Transform::default();
135            tf.translate(obj.position.x, obj.position.y);
136            tf.rotate_with_center(obj.angle, size / 2.0, size / 2.0);
137            buf.push(Vertex {
138                color: Color::WHITE,
139                position: tf.transform_point(Vector2f::new(0., 0.)),
140                tex_coords: Vector2f::new(tex_x, 0.),
141            });
142            buf.push(Vertex {
143                color: Color::WHITE,
144                position: tf.transform_point(Vector2f::new(0., size)),
145                tex_coords: Vector2f::new(tex_x, size),
146            });
147            buf.push(Vertex {
148                color: Color::WHITE,
149                position: tf.transform_point(Vector2f::new(size, size)),
150                tex_coords: Vector2f::new(tex_x + size, size),
151            });
152            buf.push(Vertex {
153                color: Color::WHITE,
154                position: tf.transform_point(Vector2f::new(size, 0.)),
155                tex_coords: Vector2f::new(tex_x + size, 0.),
156            });
157            obj.update(window.size().y as f32, window.size().x as f32);
158        }
159        window.clear(Color::BLACK);
160        rs.texture = Some(&texture);
161        window.draw_primitives(&buf, PrimitiveType::QUADS, &rs);
162        rs.texture = None;
163        text.set_string(&format!("{} sprites\n{fps} fps", objects.len()));
164        window.draw_text(&text, &rs);
165        window.display();
166        buf.clear();
167        frames_rendered += 1;
168        if sec_clock.elapsed_time().as_milliseconds() >= 1000 {
169            fps = frames_rendered;
170            sec_clock.restart();
171            frames_rendered = 0;
172        }
173    }
174    Ok(())
175}
examples/opengl.rs (line 160)
16fn main() -> SfResult<()> {
17    example_ensure_right_working_dir();
18
19    let mut exit = false;
20    let mut srgb = false;
21
22    while !exit {
23        let ctx_sett = ContextSettings {
24            depth_bits: 24,
25            srgb_capable: srgb,
26            ..Default::default()
27        };
28
29        let mut window = RenderWindow::new(
30            (800, 600),
31            "SFML graphics with OpenGL",
32            Style::default(),
33            &ctx_sett,
34        )?;
35        window.set_vertical_sync_enabled(true);
36
37        let mut bg_tex = Texture::new()?;
38        bg_tex.set_srgb(srgb);
39        bg_tex.load_from_file("opengl-background.jpg", IntRect::default())?;
40        let bg_sprite = Sprite::with_texture(&bg_tex);
41
42        let font = Font::from_file("sansation.ttf")?;
43        let mut text = Text::new("SFML / OpenGL demo", &font, 32);
44        let mut srgb_instr = Text::new("Press space to toggle sRGB conversion", &font, 32);
45        let mut mipmap_instr = Text::new("Press return to toggle mipmapping", &font, 32);
46        text.set_fill_color(Color::rgba(255, 255, 255, 170));
47        srgb_instr.set_fill_color(Color::rgba(255, 255, 255, 170));
48        mipmap_instr.set_fill_color(Color::rgba(255, 255, 255, 170));
49        text.set_position((250., 450.));
50        srgb_instr.set_position((150., 500.));
51        mipmap_instr.set_position((180., 550.));
52
53        let mut texture = Texture::from_file("texture.jpg")?;
54        texture.generate_mipmap()?;
55        window.set_active(true)?;
56        unsafe {
57            gl::glEnable(gl::GL_DEPTH_TEST);
58            gl::glDepthMask(gl::GL_TRUE as _);
59            gl::glClearDepth(1.);
60            gl::glDisable(gl::GL_LIGHTING);
61            gl::glViewport(0, 0, window.size().x as _, window.size().y as _);
62            gl::glMatrixMode(gl::GL_PROJECTION);
63            gl::glLoadIdentity();
64            let ratio = (window.size().x / window.size().y) as gl::GLdouble;
65            gl::glFrustum(-ratio, ratio, -1., 1., 1., 500.);
66            gl::glEnable(gl::GL_TEXTURE_2D);
67            Texture::bind(&texture);
68        }
69
70        let cube: [f32; 180] = [
71            -20., -20., -20., 0., 0., -20., 20., -20., 1., 0., -20., -20., 20., 0., 1., -20., -20.,
72            20., 0., 1., -20., 20., -20., 1., 0., -20., 20., 20., 1., 1., 20., -20., -20., 0., 0.,
73            20., 20., -20., 1., 0., 20., -20., 20., 0., 1., 20., -20., 20., 0., 1., 20., 20., -20.,
74            1., 0., 20., 20., 20., 1., 1., -20., -20., -20., 0., 0., 20., -20., -20., 1., 0., -20.,
75            -20., 20., 0., 1., -20., -20., 20., 0., 1., 20., -20., -20., 1., 0., 20., -20., 20.,
76            1., 1., -20., 20., -20., 0., 0., 20., 20., -20., 1., 0., -20., 20., 20., 0., 1., -20.,
77            20., 20., 0., 1., 20., 20., -20., 1., 0., 20., 20., 20., 1., 1., -20., -20., -20., 0.,
78            0., 20., -20., -20., 1., 0., -20., 20., -20., 0., 1., -20., 20., -20., 0., 1., 20.,
79            -20., -20., 1., 0., 20., 20., -20., 1., 1., -20., -20., 20., 0., 0., 20., -20., 20.,
80            1., 0., -20., 20., 20., 0., 1., -20., 20., 20., 0., 1., 20., -20., 20., 1., 0., 20.,
81            20., 20., 1., 1.,
82        ];
83
84        unsafe {
85            gl::glEnableClientState(gl::GL_VERTEX_ARRAY);
86            gl::glEnableClientState(gl::GL_TEXTURE_COORD_ARRAY);
87            gl::glVertexPointer(
88                3,
89                gl::GL_FLOAT,
90                5 * size_of::<gl::GLfloat>() as i32,
91                cube.as_ptr() as *const c_void,
92            );
93            gl::glTexCoordPointer(
94                2,
95                gl::GL_FLOAT,
96                5 * size_of::<gl::GLfloat>() as i32,
97                cube.as_ptr().offset(3) as *const c_void,
98            );
99
100            // Disable normal and color vertex components
101            gl::glDisableClientState(gl::GL_NORMAL_ARRAY);
102            gl::glDisableClientState(gl::GL_COLOR_ARRAY);
103        }
104
105        window.set_active(false)?;
106        let clock = Clock::start()?;
107        let mut mipmap_enabled = true;
108
109        while window.is_open() {
110            while let Some(event) = window.poll_event() {
111                match event {
112                    Event::Closed
113                    | Event::KeyPressed {
114                        code: Key::Escape, ..
115                    } => {
116                        exit = true;
117                        window.close();
118                    }
119                    Event::KeyPressed {
120                        code: Key::Enter, ..
121                    } => {
122                        if mipmap_enabled {
123                            texture = Texture::from_file("texture.jpg")?;
124                            mipmap_enabled = false;
125                            window.set_active(true)?;
126                            Texture::bind(&texture);
127                            window.set_active(false)?;
128                        } else {
129                            texture.generate_mipmap()?;
130                            mipmap_enabled = true;
131                        }
132                    }
133                    Event::KeyPressed {
134                        code: Key::Space, ..
135                    } => {
136                        srgb = !srgb;
137                        window.close();
138                    }
139                    Event::Resized { width, height } => {
140                        window.set_active(true)?;
141                        unsafe {
142                            gl::glViewport(0, 0, width as _, height as _);
143                        }
144                        window.set_active(false)?;
145                    }
146                    _ => {}
147                }
148            }
149            window.push_gl_states();
150            window.draw(&bg_sprite);
151            window.pop_gl_states();
152
153            if let Err(e) = window.set_active(true) {
154                eprintln!("Failed to set window as active: {e}");
155            }
156
157            unsafe {
158                gl::glClear(gl::GL_DEPTH_BUFFER_BIT);
159                let x: f32 =
160                    window.mouse_position().x as f32 * 200. / window.size().x as f32 - 100.;
161                let y: f32 =
162                    -window.mouse_position().y as f32 * 200. / window.size().y as f32 + 100.;
163
164                gl::glMatrixMode(gl::GL_MODELVIEW);
165                gl::glLoadIdentity();
166                gl::glTranslatef(x, y, -100.);
167                gl::glRotatef(clock.elapsed_time().as_seconds() * 50., 1., 0., 0.);
168                gl::glRotatef(clock.elapsed_time().as_seconds() * 30., 0., 1., 0.);
169                gl::glRotatef(clock.elapsed_time().as_seconds() * 90., 0., 0., 1.);
170                gl::glDrawArrays(gl::GL_TRIANGLES, 0, 36);
171            }
172            if let Err(e) = window.set_active(false) {
173                eprintln!("Failed to set window as active: {e}");
174            }
175            window.push_gl_states();
176            window.draw(&text);
177            window.draw(&srgb_instr);
178            window.draw(&mipmap_instr);
179            window.pop_gl_states();
180            window.display();
181        }
182    }
183    Ok(())
184}
examples/cursor.rs (line 201)
72fn main() -> SfResult<()> {
73    example_ensure_right_working_dir();
74
75    let mut cursor = Cursor::from_system(CursorType::Arrow)?;
76    let mut rw = RenderWindow::new(
77        (800, 800),
78        "SFML cursor example",
79        Style::CLOSE,
80        &ContextSettings::default(),
81    )?;
82    rw.set_vertical_sync_enabled(true);
83    let font = Font::from_file("sansation.ttf")?;
84    let mut failed_index = usize::MAX;
85    let mut selected_index = usize::MAX;
86    let set_button = Rect::new(348, 500, 100, 32);
87    let hotspot_button = Rect::new(458, 500, 100, 32);
88    let clear_button = Rect::new(568, 500, 100, 32);
89    let mut pixel_grid = [false; DRAW_GRID_WH as usize * DRAW_GRID_WH as usize];
90    let mut hotspot_selection = false;
91    let mut hotspot_selected = false;
92    let mut hotspot = Vector2::new(8, 8);
93    let mut modif = false;
94
95    let mut buttons = Vec::new();
96    let cursor_types = [
97        CursorType::Arrow,
98        CursorType::ArrowWait,
99        CursorType::Wait,
100        CursorType::Text,
101        CursorType::Hand,
102        CursorType::SizeHorizontal,
103        CursorType::SizeVertical,
104        CursorType::SizeTopLeftBottomRight,
105        CursorType::SizeBottomLeftTopRight,
106        CursorType::SizeLeft,
107        CursorType::SizeRight,
108        CursorType::SizeTop,
109        CursorType::SizeBottom,
110        CursorType::SizeTopLeft,
111        CursorType::SizeBottomRight,
112        CursorType::SizeBottomLeft,
113        CursorType::SizeTopRight,
114        CursorType::SizeAll,
115        CursorType::Cross,
116        CursorType::Help,
117        CursorType::NotAllowed,
118    ];
119    for i in 0..cursor_types.len() {
120        buttons.push(Rect::new(16, 16 + i as i32 * 36, 250, 32));
121    }
122
123    while rw.is_open() {
124        while let Some(ev) = rw.poll_event() {
125            match ev {
126                Event::Closed => rw.close(),
127                Event::MouseButtonPressed {
128                    button: mouse::Button::Left,
129                    x,
130                    y,
131                } => {
132                    for (i, b) in buttons.iter().enumerate() {
133                        if mouse_over(b, x, y) {
134                            match cursor.load_from_system(cursor_types[i]) {
135                                Ok(()) => {
136                                    unsafe {
137                                        rw.set_mouse_cursor(&cursor);
138                                    }
139                                    selected_index = i;
140                                }
141                                Err(e) => {
142                                    eprintln!("{e}");
143                                    failed_index = i;
144                                }
145                            }
146                        }
147                    }
148                    if mouse_over(&set_button, x, y) {
149                        let mut pixels = [0; DRAW_GRID_WH as usize * DRAW_GRID_WH as usize * 4];
150                        for (i, px) in pixel_grid.iter().enumerate() {
151                            let offset = i * 4;
152                            if *px {
153                                pixels[offset] = 255;
154                                pixels[offset + 1] = 255;
155                                pixels[offset + 2] = 255;
156                                pixels[offset + 3] = 255;
157                            }
158                        }
159                        unsafe {
160                            match cursor.load_from_pixels(
161                                &pixels,
162                                Vector2::new(DRAW_GRID_WH as u32, DRAW_GRID_WH as u32),
163                                hotspot,
164                            ) {
165                                Ok(()) => {
166                                    rw.set_mouse_cursor(&cursor);
167                                }
168                                Err(e) => {
169                                    eprintln!("{e}");
170                                }
171                            }
172                        }
173                        modif = false;
174                    }
175                    if mouse_over(&clear_button, x, y) {
176                        for px in pixel_grid.iter_mut() {
177                            *px = false;
178                        }
179                        modif = true;
180                    }
181                    if mouse_over(&hotspot_button, x, y) {
182                        hotspot_selection = true;
183                    }
184                }
185                Event::MouseButtonReleased {
186                    button: mouse::Button::Left,
187                    ..
188                } => {
189                    if hotspot_selected {
190                        hotspot_selection = false;
191                        hotspot_selected = false;
192                    }
193                }
194                _ => {}
195            }
196        }
197        let mut set_button_highlighted = false;
198        let mut hotspot_button_highlighted = false;
199        let mut clear_button_highlighted = false;
200        // System cursor set button interactions
201        let mp = rw.mouse_position();
202        let mut highlight_index = usize::MAX;
203        for (i, b) in buttons.iter().enumerate() {
204            if mouse_over(b, mp.x, mp.y) {
205                highlight_index = i;
206            }
207        }
208        if mouse_over(&set_button, mp.x, mp.y) {
209            set_button_highlighted = true;
210        }
211        if mouse_over(&hotspot_button, mp.x, mp.y) {
212            hotspot_button_highlighted = true;
213        }
214        if mouse_over(&clear_button, mp.x, mp.y) {
215            clear_button_highlighted = true;
216        }
217        // Grid interactions
218        let rela_x = mp.x - DRAW_AREA_TOPLEFT.0 as i32;
219        let rela_y = mp.y - DRAW_AREA_TOPLEFT.1 as i32;
220        let (gx, gy) = (rela_x / DRAW_CELL_WH as i32, rela_y / DRAW_CELL_WH as i32);
221        if gx >= 0 && gy >= 0 {
222            if let Some(cell) = gridindex(&mut pixel_grid, gx as usize, gy as usize) {
223                if hotspot_selection {
224                    hotspot_selected = true;
225                    hotspot = Vector2::new(gx as u32, gy as u32);
226                    modif = true;
227                } else if mouse::Button::Left.is_pressed() {
228                    *cell = true;
229                    modif = true;
230                } else if mouse::Button::Right.is_pressed() {
231                    *cell = false;
232                    modif = true;
233                }
234            }
235        }
236        rw.clear(Color::BLACK);
237        // Draw system cursor set buttons
238        let mut shape = RectangleShape::default();
239        let mut text = Text::new("", &font, 14);
240        shape.set_outline_thickness(-1.0);
241        shape.set_outline_color(Color::WHITE);
242        for (i, b) in buttons.iter().enumerate() {
243            let types = [
244                "ARROW",
245                "ARROW_WAIT",
246                "WAIT",
247                "TEXT",
248                "HAND",
249                "SIZE_HORIZONTAL",
250                "SIZE_VERTICAL",
251                "SIZE_TOP_LEFT_BOTTOM_RIGHT",
252                "SIZE_BOTTOM_LEFT_TOP_RIGHT",
253                "SIZE_LEFT",
254                "SIZE_RIGHT",
255                "SIZE_TOP",
256                "SIZE_BOTTOM",
257                "SIZE_TOP_LEFT",
258                "SIZE_BOTTOM_RIGHT",
259                "SIZE_BOTTOM_LEFT",
260                "SIZE_TOP_RIGHT",
261                "SIZE_ALL",
262                "CROSS",
263                "HELP",
264                "NOT_ALLOWED",
265            ];
266            draw_button(
267                b,
268                &mut shape,
269                &mut text,
270                types[i],
271                &mut rw,
272                bstyle(highlight_index == i, selected_index == i, failed_index == i),
273            );
274        }
275        // Draw pixel drawing grid
276        shape.set_fill_color(Color::TRANSPARENT);
277        for y in 0..DRAW_GRID_WH {
278            for x in 0..DRAW_GRID_WH {
279                if hotspot.x == x as u32 && hotspot.y == y as u32 {
280                    shape.set_outline_color(Color::RED);
281                } else {
282                    shape.set_outline_color(Color::rgb(180, 180, 180));
283                }
284                if gridindex(&mut pixel_grid, x as usize, y as usize).is_some_and(|bool| *bool) {
285                    shape.set_fill_color(Color::WHITE);
286                } else {
287                    shape.set_fill_color(Color::TRANSPARENT);
288                }
289                shape.set_size((DRAW_CELL_WH as f32, DRAW_CELL_WH as f32));
290                shape.set_position((
291                    DRAW_AREA_TOPLEFT.0 as f32 + (x as f32 * DRAW_CELL_WH as f32),
292                    DRAW_AREA_TOPLEFT.1 as f32 + (y as f32 * DRAW_CELL_WH as f32),
293                ));
294                rw.draw(&shape);
295            }
296        }
297        draw_button(
298            &set_button,
299            &mut shape,
300            &mut text,
301            if modif { "Set*" } else { "Set" },
302            &mut rw,
303            bstyle(set_button_highlighted, false, false),
304        );
305        draw_button(
306            &hotspot_button,
307            &mut shape,
308            &mut text,
309            "Hotspot",
310            &mut rw,
311            bstyle(hotspot_button_highlighted, hotspot_selection, false),
312        );
313        draw_button(
314            &clear_button,
315            &mut shape,
316            &mut text,
317            "Clear",
318            &mut rw,
319            bstyle(clear_button_highlighted, false, false),
320        );
321        rw.display();
322    }
323    Ok(())
324}
Source

pub fn set_mouse_position(&mut self, position: Vector2i)

Set the current position of the mouse relatively to a render window

This function sets the current position of the mouse cursor relative to the given render window

§Arguments
  • position - the positon to set
Examples found in repository?
examples/mouse.rs (line 46)
5fn main() -> SfResult<()> {
6    example_ensure_right_working_dir();
7
8    let mut window = RenderWindow::new(
9        (800, 600),
10        "Mouse events",
11        Style::CLOSE,
12        &Default::default(),
13    )?;
14    window.set_mouse_cursor_visible(false);
15    window.set_vertical_sync_enabled(true);
16
17    let font = Font::from_file("sansation.ttf")?;
18    let mut circle = CircleShape::new(4., 30);
19    let mut texts: Vec<Text> = Vec::new();
20    let mut mp_text = Text::new("", &font, 14);
21    let mut cursor_visible = false;
22    let mut grabbed = false;
23    macro_rules! push_text {
24        ($x:expr, $y:expr, $fmt:expr, $($arg:tt)*) => {
25            let mut text = Text::new(&format!($fmt, $($arg)*), &font, 14);
26            text.set_position(($x as f32, $y as f32));
27            texts.push(text);
28        }
29    }
30
31    'mainloop: loop {
32        while let Some(ev) = window.poll_event() {
33            match ev {
34                Event::Closed => break 'mainloop,
35                Event::MouseWheelScrolled { wheel, delta, x, y } => {
36                    push_text!(x, y, "Scroll: {:?}, {}, {}, {}", wheel, delta, x, y);
37                }
38                Event::MouseButtonPressed { button, x, y } => {
39                    push_text!(x, y, "Press: {:?}, {}, {}", button, x, y);
40                }
41                Event::MouseButtonReleased { button, x, y } => {
42                    push_text!(x, y, "Release: {:?}, {}, {}", button, x, y);
43                }
44                Event::KeyPressed { code, .. } => {
45                    if code == Key::W {
46                        window.set_mouse_position(Vector2i::new(400, 300));
47                    } else if code == Key::D {
48                        let dm = VideoMode::desktop_mode();
49                        let center = Vector2i::new(dm.width as i32 / 2, dm.height as i32 / 2);
50                        mouse::set_desktop_position(center);
51                    } else if code == Key::V {
52                        cursor_visible = !cursor_visible;
53                        window.set_mouse_cursor_visible(cursor_visible);
54                    } else if code == Key::G {
55                        grabbed = !grabbed;
56                        window.set_mouse_cursor_grabbed(grabbed);
57                    }
58                }
59                _ => {}
60            }
61        }
62
63        let mp = window.mouse_position();
64        let dmp = mouse::desktop_position();
65        let cur_vis_msg = if cursor_visible {
66            "visible"
67        } else {
68            "invisible"
69        };
70        let grab_msg = if grabbed { "grabbed" } else { "not grabbed" };
71        mp_text.set_string(&format!(
72            "x: {}, y: {} (Window)\n\
73             x: {}, y: {} (Desktop)\n\
74             [{cur_vis_msg}] [{grab_msg}] ('V'/'G') to toggle\n\
75             'W' to center mouse on window\n\
76             'D' to center mouse on desktop",
77            mp.x, mp.y, dmp.x, dmp.y
78        ));
79
80        circle.set_position((mp.x as f32, mp.y as f32));
81
82        window.clear(Color::BLACK);
83        // Push texts out of each other's way
84        for i in (0..texts.len()).rev() {
85            for j in (0..i).rev() {
86                if let Some(intersect) = texts[i]
87                    .global_bounds()
88                    .intersection(&texts[j].global_bounds())
89                {
90                    texts[j].move_((0., -intersect.height));
91                }
92            }
93        }
94        texts.retain(|txt| txt.fill_color().a > 0);
95        for txt in &mut texts {
96            let mut color = txt.fill_color();
97            color.a -= 1;
98            txt.set_fill_color(color);
99            window.draw(txt);
100        }
101        if !cursor_visible {
102            window.draw(&circle);
103        }
104        window.draw(&mp_text);
105        window.display();
106    }
107    Ok(())
108}
Source

pub fn touch_position(&self, finger: u32) -> Vector2i

Returns the current position of a touch in window coordinates.

Source§

impl RenderWindow

Window operations

Source

pub unsafe fn set_icon(&mut self, width: u32, height: u32, pixels: &[u8])

Change a render window’s icon pixels must be an array of width x height pixels in 32-bits RGBA format.

§Arguments
  • width - Icon’s width, in pixels
  • height - Icon’s height, in pixels
  • pixels - Vector of pixels
§Safety

pixels not being at least width * height * 4 will likely cause undefined behavior.

Platform-specific behavior is also unclear (limits on max size, etc).

Source

pub fn close(&mut self)

Close a render window and destroy all the attached resources

After calling this method, the Window object remains valid. All other functions such as poll_event or display will still work (i.e. you don’t have to test is_open every time), and will have no effect on closed windows.

Examples found in repository?
examples/resource-holder.rs (line 77)
55fn main() -> SfResult<()> {
56    example_ensure_right_working_dir();
57
58    let mut tex_holder = ResourceHolder::<Texture, _>::default();
59    tex_holder.load("frank", "frank.jpeg")?;
60    let mut sb_holder = ResourceHolder::<SoundBuffer, _>::default();
61    sb_holder.load("canary", "canary.wav")?;
62    let mut rw = RenderWindow::new(
63        (800, 600),
64        "Resource holder test",
65        Style::CLOSE,
66        &Default::default(),
67    )?;
68    rw.set_vertical_sync_enabled(true);
69    let mut sound = Sound::with_buffer(sb_holder.get("canary"));
70    sound.play();
71    while rw.is_open() {
72        while let Some(ev) = rw.poll_event() {
73            match ev {
74                Event::Closed
75                | Event::KeyPressed {
76                    code: Key::Escape, ..
77                } => rw.close(),
78                _ => {}
79            }
80        }
81        rw.clear(Color::BLACK);
82        rw.draw(&Sprite::with_texture(tex_holder.get("frank")));
83        rw.display();
84    }
85    Ok(())
86}
More examples
Hide additional examples
examples/shader.rs (line 299)
258fn main() -> SfResult<()> {
259    example_ensure_right_working_dir();
260
261    let mut window = RenderWindow::new(
262        (800, 600),
263        "SFML Shader",
264        Style::TITLEBAR | Style::CLOSE,
265        &Default::default(),
266    )?;
267    window.set_vertical_sync_enabled(true);
268    let font = Font::from_file("sansation.ttf")?;
269    let bg = Texture::from_file("background.jpg")?;
270    let mut bg_texture = Texture::from_file("sfml.png")?;
271    bg_texture.set_smooth(true);
272    let mut entity_texture = Texture::from_file("devices.png")?;
273    entity_texture.set_smooth(true);
274    let effects: [&mut dyn Effect; 4] = [
275        &mut Pixelate::new(&bg)?,
276        &mut WaveBlur::new(&font)?,
277        &mut StormBlink::new()?,
278        &mut Edge::new(&bg_texture, &entity_texture)?,
279    ];
280    let mut current = 0;
281    let text_bg_texture = Texture::from_file("text-background.png")?;
282    let mut text_bg = Sprite::with_texture(&text_bg_texture);
283    text_bg.set_position((0., 520.));
284    text_bg.set_color(Color::rgba(255, 255, 255, 200));
285    let msg = format!("Current effect: {}", effects[current].name());
286    let mut desc = Text::new(&msg, &font, 20);
287    desc.set_position((10., 530.));
288    desc.set_fill_color(Color::rgb(80, 80, 80));
289    let msg = "Press left and right arrows to change the current shader";
290    let mut instructions = Text::new(msg, &font, 20);
291    instructions.set_position((280., 555.));
292    instructions.set_fill_color(Color::rgb(80, 80, 80));
293    let clock = Clock::start()?;
294
295    while window.is_open() {
296        while let Some(event) = window.poll_event() {
297            use crate::Event::*;
298            match event {
299                Closed => window.close(),
300                KeyPressed { code, .. } => match code {
301                    Key::Escape => window.close(),
302                    Key::Left => {
303                        if current == 0 {
304                            current = effects.len() - 1;
305                        } else {
306                            current -= 1;
307                        }
308                        desc.set_string(&format!("Current effect: {}", effects[current].name()));
309                    }
310                    Key::Right => {
311                        if current == effects.len() - 1 {
312                            current = 0;
313                        } else {
314                            current += 1;
315                        }
316                        desc.set_string(&format!("Current effect: {}", effects[current].name()));
317                    }
318                    _ => {}
319                },
320                _ => {}
321            }
322        }
323
324        let x = window.mouse_position().x as f32 / window.size().x as f32;
325        let y = window.mouse_position().y as f32 / window.size().y as f32;
326
327        effects[current].update(clock.elapsed_time().as_seconds(), x, y)?;
328
329        window.clear(Color::rgb(255, 128, 0));
330        window.draw(effects[current].as_drawable());
331        window.draw(&text_bg);
332        window.draw(&instructions);
333        window.draw(&desc);
334        window.display();
335    }
336    Ok(())
337}
examples/rc-resources.rs (line 160)
121fn main() -> SfResult<()> {
122    example_ensure_right_working_dir();
123
124    let mut window =
125        RenderWindow::new((800, 600), "SFML window", Style::CLOSE, &Default::default())?;
126    window.set_framerate_limit(60);
127
128    // Create a new texture.
129    let texture = RcTexture::from_file("logo.png")?;
130    let texture2 = test_getting_rc_texture_from_texture()?;
131
132    // Create a new font.
133    let font_path = match std::env::args().nth(1) {
134        Some(path) => path,
135        None => "sansation.ttf".into(),
136    };
137    let mut font = RcFont::from_file(&font_path)?;
138
139    // Load many resources with no lifetime contingencies
140    let mut floating_resources = Vec::from([
141        FloatingResource::with_texture(&texture2, true, true, 1.1f32),
142        FloatingResource::with_texture(&texture2, true, true, 1.2f32),
143        FloatingResource::with_texture(&texture, true, true, 1f32),
144        FloatingResource::with_texture(&texture, true, false, 1.5f32),
145        FloatingResource::with_texture(&texture, false, true, 2f32),
146        FloatingResource::with_texture(&texture, false, false, 2.5f32),
147        FloatingResource::with_font(&font, true, true, 1.25f32),
148        FloatingResource::with_font(&font, true, true, 1.75f32),
149        FloatingResource::with_font(&font, true, true, 2.25f32),
150        FloatingResource::with_font(&font, true, true, 2.75f32),
151    ]);
152
153    let set_smooth_text = get_set_smooth_rc_text(&font);
154    let mut show_texture_atlas = false;
155    let mut text_buf = String::from("SFML");
156
157    while window.is_open() {
158        while let Some(event) = window.poll_event() {
159            if event == Event::Closed {
160                window.close();
161            }
162
163            match event {
164                Event::Closed => window.close(),
165                Event::KeyPressed { code, ctrl, .. } => match code {
166                    Key::S => {
167                        let smooth = !font.is_smooth();
168                        font.set_smooth(smooth);
169                    }
170                    Key::T => {
171                        show_texture_atlas ^= true;
172                    }
173                    Key::V if ctrl => {
174                        text_buf.push_str(&clipboard::get_string());
175                    }
176                    _ => {}
177                },
178                Event::TextEntered { unicode } if show_texture_atlas => {
179                    if unicode == 0x8 as char {
180                        text_buf.pop();
181                    } else if !unicode.is_ascii_control() && unicode != 's' && unicode != 't' {
182                        text_buf.push(unicode);
183                    }
184                }
185                _ => {}
186            }
187        }
188
189        // Update floating_resource positions so they move around on the screen
190        for floating_resource in &mut floating_resources {
191            floating_resource.move_resources(Vector2f::new(800f32, 600f32));
192            floating_resource.text.set_string(&text_buf);
193        }
194
195        window.clear(Color::BLACK);
196
197        // Fetch and draw all the sprites in floating_resources
198        for floating_resource in &floating_resources {
199            floating_resource.render(&mut window);
200        }
201
202        window.draw(&set_smooth_text);
203        if show_texture_atlas {
204            let scale = 3.0;
205            let tex = font.texture(16);
206            let mut rs = RectangleShape::with_size(tex.size().as_other());
207            rs.set_fill_color(Color::MAGENTA);
208            rs.set_scale(scale);
209            window.draw(&rs);
210            let mut s = Sprite::with_texture(&*tex);
211            s.set_scale(scale);
212            window.draw(&s);
213        }
214        window.display();
215    }
216    Ok(())
217}
examples/window-test.rs (line 44)
13fn main() -> SfResult<()> {
14    let configs = [
15        WindowConfig {
16            mode: (320, 240),
17            title: "(Windowed) Retro",
18            style: Style::CLOSE,
19        },
20        WindowConfig {
21            mode: (640, 480),
22            title: "(Windowed) Classic",
23            style: Style::DEFAULT,
24        },
25        WindowConfig {
26            mode: (800, 600),
27            title: "(Windowed) Big",
28            style: Style::TITLEBAR,
29        },
30    ];
31    let mut cfg_idx = 2usize;
32    let mut rw = RenderWindow::new(
33        configs[cfg_idx].mode,
34        "Window test",
35        Style::CLOSE,
36        &ContextSettings::default(),
37    )?;
38    let font = Font::from_memory_static(include_bytes!("resources/sansation.ttf"))?;
39    let fs_modes = VideoMode::fullscreen_modes();
40
41    while rw.is_open() {
42        while let Some(ev) = rw.poll_event() {
43            match ev {
44                Event::Closed => rw.close(),
45                Event::KeyPressed { code, .. } => match code {
46                    Key::Up => cfg_idx = cfg_idx.saturating_sub(1),
47                    Key::Down => {
48                        if cfg_idx + 1 < configs.len() + fs_modes.len() {
49                            cfg_idx += 1
50                        }
51                    }
52                    Key::Enter => match configs.get(cfg_idx) {
53                        Some(cfg) => {
54                            rw.recreate(cfg.mode, cfg.title, cfg.style, &ContextSettings::default())
55                        }
56                        None => match fs_modes.get(cfg_idx - configs.len()) {
57                            Some(mode) => rw.recreate(
58                                *mode,
59                                "Fullscreen",
60                                Style::FULLSCREEN,
61                                &ContextSettings::default(),
62                            ),
63                            None => {
64                                eprintln!("Invalid index: {cfg_idx}");
65                            }
66                        },
67                    },
68                    _ => {}
69                },
70                _ => {}
71            }
72        }
73        rw.clear(Color::BLACK);
74        let fontsize = 16;
75        let mut txt = Text::new("Arrow keys to select mode, enter to set.", &font, fontsize);
76        rw.draw(&txt);
77        let mut y = fontsize as f32;
78        for (i, cfg) in configs.iter().enumerate() {
79            let fc = if i == cfg_idx {
80                Color::YELLOW
81            } else {
82                Color::WHITE
83            };
84            txt.set_fill_color(fc);
85            txt.set_string(&format!(
86                "{}x{} \"{}\" ({:?})",
87                cfg.mode.0, cfg.mode.1, cfg.title, cfg.style
88            ));
89            txt.set_position((0., y));
90            rw.draw(&txt);
91            y += fontsize as f32;
92        }
93        let mut i = configs.len();
94        y += fontsize as f32;
95        txt.set_position((0., y));
96        txt.set_fill_color(Color::WHITE);
97        txt.set_string("= Fullscreen modes =");
98        rw.draw(&txt);
99        for mode in fs_modes.iter() {
100            let n_rows = 23;
101            let column = i / n_rows;
102            let row = i % n_rows;
103            let fc = if i == cfg_idx {
104                Color::YELLOW
105            } else {
106                Color::WHITE
107            };
108            txt.set_fill_color(fc);
109            let left_pad = 16.0;
110            let x = left_pad + (column * 128) as f32;
111            let gap = 16.0;
112            let y = y + gap + (row * fontsize as usize) as f32;
113            txt.set_position((x, y));
114            txt.set_string(&format!(
115                "{}x{}x{}",
116                mode.width, mode.height, mode.bits_per_pixel
117            ));
118            rw.draw(&txt);
119            i += 1;
120        }
121        rw.display();
122    }
123    Ok(())
124}
examples/positional-audio.rs (line 77)
46fn main() -> Result<(), Box<dyn Error>> {
47    example_ensure_right_working_dir();
48
49    let mut rw = RenderWindow::new(
50        (800, 600),
51        "Positional audio demo",
52        Style::CLOSE,
53        &Default::default(),
54    )?;
55    rw.set_vertical_sync_enabled(true);
56    let font = Font::from_file("sansation.ttf")?;
57    let mut text = Text::new("", &font, 20);
58    let mut music = match std::env::args().nth(1) {
59        Some(music_path) => Music::from_file(&music_path)?,
60        None => Music::from_file("canary.wav")?,
61    };
62    if music.channel_count() != 1 {
63        return Err("Sorry, only sounds with 1 channel are supported.".into());
64    };
65    music.set_looping(true);
66    music.play();
67    music.set_position(Vector3::new(0., 0., 0.));
68
69    let mut listener_pos = Vector3::new(0.0, 0.0, 0.0);
70    let center = Vector2::new(400., 300.);
71    let [mut go_left, mut go_right, mut go_up, mut go_down] = [false; 4];
72    let clock = Clock::start()?;
73
74    while rw.is_open() {
75        while let Some(ev) = rw.poll_event() {
76            match ev {
77                Event::Closed => rw.close(),
78                Event::KeyPressed { code, .. } => match code {
79                    Key::A => go_left = true,
80                    Key::D => go_right = true,
81                    Key::W => go_up = true,
82                    Key::S => go_down = true,
83                    _ => {}
84                },
85                Event::KeyReleased { code, .. } => match code {
86                    Key::A => go_left = false,
87                    Key::D => go_right = false,
88                    Key::W => go_up = false,
89                    Key::S => go_down = false,
90                    _ => {}
91                },
92                _ => {}
93            }
94        }
95        let Vector2f { x: mx, y: my } = rw.mouse_position().as_other();
96        let speed = 0.05;
97        if go_left {
98            listener_pos.x -= speed;
99        }
100        if go_right {
101            listener_pos.x += speed;
102        }
103        if go_up {
104            listener_pos.y -= speed;
105        }
106        if go_down {
107            listener_pos.y += speed;
108        }
109        let scale = 20.0; // Scale the positions for better visualization
110        listener::set_position(listener_pos);
111        listener::set_direction(Vector3::new(
112            (mx - center.x) / scale,
113            (my - center.y) / scale,
114            -1.,
115        ));
116        let Vector3 {
117            x: lx,
118            y: ly,
119            z: lz,
120        } = listener::position();
121        let Vector3 {
122            x: dx,
123            y: dy,
124            z: dz,
125        } = listener::direction();
126        rw.clear(Color::BLACK);
127        let mut circle_shape = CircleShape::new(8.0, 32);
128        // Draw circle at center, representing position of music being played
129        circle_shape.set_position(center);
130        circle_shape.set_fill_color(Color::YELLOW);
131        let t = clock.elapsed_time().as_seconds();
132        let radius = 12.0 + t.sin() * 3.0;
133        circle_shape.set_radius(radius);
134        circle_shape.set_origin(radius);
135        rw.draw(&circle_shape);
136        // Draw circle representing listener
137        circle_shape.set_position((center.x + lx * scale, center.y + ly * scale));
138        circle_shape.set_origin(4.0);
139        circle_shape.set_radius(4.0);
140        circle_shape.set_fill_color(Color::GREEN);
141        rw.draw(&circle_shape);
142        // Draw line from listener to direction vector position
143        rw.draw_line(
144            circle_shape.position(),
145            (center.x + dx * scale, center.y + dy * scale).into(),
146            2.0,
147        );
148        text.set_string("WASD + mouse for movement of listener");
149        text.set_position(0.);
150        rw.draw(&text);
151        text.set_string(&format!("Listener position: {lx}, {ly}, {lz}"));
152        text.set_position((0., 20.0));
153        rw.draw(&text);
154        text.set_string(&format!("Listener direction: {dx}, {dy}, {dz}"));
155        text.set_position((0., 40.0));
156        rw.draw(&text);
157        rw.display();
158    }
159    Ok(())
160}
examples/spritemark.rs (line 96)
62fn main() -> SfResult<()> {
63    example_ensure_right_working_dir();
64
65    let native_mode = VideoMode::desktop_mode();
66    let mut window = RenderWindow::new(
67        native_mode,
68        "Spritemark",
69        Style::default(),
70        &ContextSettings::default(),
71    )?;
72    window.set_position(Vector2::new(0, 0));
73    window.set_vertical_sync_enabled(true);
74    let font = Font::from_file("sansation.ttf")?;
75    let texture = Texture::from_file("devices.png")?;
76    let mut text = Text::new("", &font, 18);
77    text.set_outline_color(Color::BLACK);
78    text.set_outline_thickness(1.0);
79    let mut click_counter = 0;
80    let mut objects = Vec::new();
81    let mut rng = thread_rng();
82    let mut rs = RenderStates::default();
83    let mut buf = Vec::new();
84    let mut frames_rendered = 0;
85    let mut sec_clock = Clock::start()?;
86    let mut fps = 0;
87    let mut lmb_down = false;
88    let mut view = View::new()?;
89
90    while window.is_open() {
91        while let Some(event) = window.poll_event() {
92            match event {
93                Event::Closed
94                | Event::KeyPressed {
95                    code: Key::Escape, ..
96                } => window.close(),
97                Event::MouseButtonPressed {
98                    button: Button::Left,
99                    ..
100                } => {
101                    click_counter += 1;
102                    lmb_down = true;
103                }
104                Event::MouseButtonReleased {
105                    button: Button::Left,
106                    ..
107                } => {
108                    lmb_down = false;
109                }
110                Event::Resized { width, height } => {
111                    view.reset(Rect::new(0., 0., width as f32, height as f32));
112                    window.set_view(&view);
113                }
114                _ => {}
115            }
116        }
117
118        if lmb_down {
119            let mp = window.mouse_position();
120            for _ in 0..25 {
121                objects.push(Object {
122                    position: fconv(mp),
123                    speed: Vector2f::new(rng.gen_range(-3.0..3.0), 0.0),
124                    image_id: click_counter % N_IMAGES,
125                    angle: 0.0,
126                    rot_speed: rng.gen_range(-2.0..2.0),
127                });
128            }
129        }
130
131        for obj in &mut objects {
132            let size = f32::from(SUBIMAGE_SIZE);
133            let tex_x = f32::from(obj.image_id) * size;
134            let mut tf = Transform::default();
135            tf.translate(obj.position.x, obj.position.y);
136            tf.rotate_with_center(obj.angle, size / 2.0, size / 2.0);
137            buf.push(Vertex {
138                color: Color::WHITE,
139                position: tf.transform_point(Vector2f::new(0., 0.)),
140                tex_coords: Vector2f::new(tex_x, 0.),
141            });
142            buf.push(Vertex {
143                color: Color::WHITE,
144                position: tf.transform_point(Vector2f::new(0., size)),
145                tex_coords: Vector2f::new(tex_x, size),
146            });
147            buf.push(Vertex {
148                color: Color::WHITE,
149                position: tf.transform_point(Vector2f::new(size, size)),
150                tex_coords: Vector2f::new(tex_x + size, size),
151            });
152            buf.push(Vertex {
153                color: Color::WHITE,
154                position: tf.transform_point(Vector2f::new(size, 0.)),
155                tex_coords: Vector2f::new(tex_x + size, 0.),
156            });
157            obj.update(window.size().y as f32, window.size().x as f32);
158        }
159        window.clear(Color::BLACK);
160        rs.texture = Some(&texture);
161        window.draw_primitives(&buf, PrimitiveType::QUADS, &rs);
162        rs.texture = None;
163        text.set_string(&format!("{} sprites\n{fps} fps", objects.len()));
164        window.draw_text(&text, &rs);
165        window.display();
166        buf.clear();
167        frames_rendered += 1;
168        if sec_clock.elapsed_time().as_milliseconds() >= 1000 {
169            fps = frames_rendered;
170            sec_clock.restart();
171            frames_rendered = 0;
172        }
173    }
174    Ok(())
175}
Source

pub fn is_open(&self) -> bool

Tell whether or not a window is opened

This function returns whether or not the window exists. Note that a hidden window (set_visible(false)) will return true.

Examples found in repository?
examples/resource-holder.rs (line 71)
55fn main() -> SfResult<()> {
56    example_ensure_right_working_dir();
57
58    let mut tex_holder = ResourceHolder::<Texture, _>::default();
59    tex_holder.load("frank", "frank.jpeg")?;
60    let mut sb_holder = ResourceHolder::<SoundBuffer, _>::default();
61    sb_holder.load("canary", "canary.wav")?;
62    let mut rw = RenderWindow::new(
63        (800, 600),
64        "Resource holder test",
65        Style::CLOSE,
66        &Default::default(),
67    )?;
68    rw.set_vertical_sync_enabled(true);
69    let mut sound = Sound::with_buffer(sb_holder.get("canary"));
70    sound.play();
71    while rw.is_open() {
72        while let Some(ev) = rw.poll_event() {
73            match ev {
74                Event::Closed
75                | Event::KeyPressed {
76                    code: Key::Escape, ..
77                } => rw.close(),
78                _ => {}
79            }
80        }
81        rw.clear(Color::BLACK);
82        rw.draw(&Sprite::with_texture(tex_holder.get("frank")));
83        rw.display();
84    }
85    Ok(())
86}
More examples
Hide additional examples
examples/shader.rs (line 295)
258fn main() -> SfResult<()> {
259    example_ensure_right_working_dir();
260
261    let mut window = RenderWindow::new(
262        (800, 600),
263        "SFML Shader",
264        Style::TITLEBAR | Style::CLOSE,
265        &Default::default(),
266    )?;
267    window.set_vertical_sync_enabled(true);
268    let font = Font::from_file("sansation.ttf")?;
269    let bg = Texture::from_file("background.jpg")?;
270    let mut bg_texture = Texture::from_file("sfml.png")?;
271    bg_texture.set_smooth(true);
272    let mut entity_texture = Texture::from_file("devices.png")?;
273    entity_texture.set_smooth(true);
274    let effects: [&mut dyn Effect; 4] = [
275        &mut Pixelate::new(&bg)?,
276        &mut WaveBlur::new(&font)?,
277        &mut StormBlink::new()?,
278        &mut Edge::new(&bg_texture, &entity_texture)?,
279    ];
280    let mut current = 0;
281    let text_bg_texture = Texture::from_file("text-background.png")?;
282    let mut text_bg = Sprite::with_texture(&text_bg_texture);
283    text_bg.set_position((0., 520.));
284    text_bg.set_color(Color::rgba(255, 255, 255, 200));
285    let msg = format!("Current effect: {}", effects[current].name());
286    let mut desc = Text::new(&msg, &font, 20);
287    desc.set_position((10., 530.));
288    desc.set_fill_color(Color::rgb(80, 80, 80));
289    let msg = "Press left and right arrows to change the current shader";
290    let mut instructions = Text::new(msg, &font, 20);
291    instructions.set_position((280., 555.));
292    instructions.set_fill_color(Color::rgb(80, 80, 80));
293    let clock = Clock::start()?;
294
295    while window.is_open() {
296        while let Some(event) = window.poll_event() {
297            use crate::Event::*;
298            match event {
299                Closed => window.close(),
300                KeyPressed { code, .. } => match code {
301                    Key::Escape => window.close(),
302                    Key::Left => {
303                        if current == 0 {
304                            current = effects.len() - 1;
305                        } else {
306                            current -= 1;
307                        }
308                        desc.set_string(&format!("Current effect: {}", effects[current].name()));
309                    }
310                    Key::Right => {
311                        if current == effects.len() - 1 {
312                            current = 0;
313                        } else {
314                            current += 1;
315                        }
316                        desc.set_string(&format!("Current effect: {}", effects[current].name()));
317                    }
318                    _ => {}
319                },
320                _ => {}
321            }
322        }
323
324        let x = window.mouse_position().x as f32 / window.size().x as f32;
325        let y = window.mouse_position().y as f32 / window.size().y as f32;
326
327        effects[current].update(clock.elapsed_time().as_seconds(), x, y)?;
328
329        window.clear(Color::rgb(255, 128, 0));
330        window.draw(effects[current].as_drawable());
331        window.draw(&text_bg);
332        window.draw(&instructions);
333        window.draw(&desc);
334        window.display();
335    }
336    Ok(())
337}
examples/rc-resources.rs (line 157)
121fn main() -> SfResult<()> {
122    example_ensure_right_working_dir();
123
124    let mut window =
125        RenderWindow::new((800, 600), "SFML window", Style::CLOSE, &Default::default())?;
126    window.set_framerate_limit(60);
127
128    // Create a new texture.
129    let texture = RcTexture::from_file("logo.png")?;
130    let texture2 = test_getting_rc_texture_from_texture()?;
131
132    // Create a new font.
133    let font_path = match std::env::args().nth(1) {
134        Some(path) => path,
135        None => "sansation.ttf".into(),
136    };
137    let mut font = RcFont::from_file(&font_path)?;
138
139    // Load many resources with no lifetime contingencies
140    let mut floating_resources = Vec::from([
141        FloatingResource::with_texture(&texture2, true, true, 1.1f32),
142        FloatingResource::with_texture(&texture2, true, true, 1.2f32),
143        FloatingResource::with_texture(&texture, true, true, 1f32),
144        FloatingResource::with_texture(&texture, true, false, 1.5f32),
145        FloatingResource::with_texture(&texture, false, true, 2f32),
146        FloatingResource::with_texture(&texture, false, false, 2.5f32),
147        FloatingResource::with_font(&font, true, true, 1.25f32),
148        FloatingResource::with_font(&font, true, true, 1.75f32),
149        FloatingResource::with_font(&font, true, true, 2.25f32),
150        FloatingResource::with_font(&font, true, true, 2.75f32),
151    ]);
152
153    let set_smooth_text = get_set_smooth_rc_text(&font);
154    let mut show_texture_atlas = false;
155    let mut text_buf = String::from("SFML");
156
157    while window.is_open() {
158        while let Some(event) = window.poll_event() {
159            if event == Event::Closed {
160                window.close();
161            }
162
163            match event {
164                Event::Closed => window.close(),
165                Event::KeyPressed { code, ctrl, .. } => match code {
166                    Key::S => {
167                        let smooth = !font.is_smooth();
168                        font.set_smooth(smooth);
169                    }
170                    Key::T => {
171                        show_texture_atlas ^= true;
172                    }
173                    Key::V if ctrl => {
174                        text_buf.push_str(&clipboard::get_string());
175                    }
176                    _ => {}
177                },
178                Event::TextEntered { unicode } if show_texture_atlas => {
179                    if unicode == 0x8 as char {
180                        text_buf.pop();
181                    } else if !unicode.is_ascii_control() && unicode != 's' && unicode != 't' {
182                        text_buf.push(unicode);
183                    }
184                }
185                _ => {}
186            }
187        }
188
189        // Update floating_resource positions so they move around on the screen
190        for floating_resource in &mut floating_resources {
191            floating_resource.move_resources(Vector2f::new(800f32, 600f32));
192            floating_resource.text.set_string(&text_buf);
193        }
194
195        window.clear(Color::BLACK);
196
197        // Fetch and draw all the sprites in floating_resources
198        for floating_resource in &floating_resources {
199            floating_resource.render(&mut window);
200        }
201
202        window.draw(&set_smooth_text);
203        if show_texture_atlas {
204            let scale = 3.0;
205            let tex = font.texture(16);
206            let mut rs = RectangleShape::with_size(tex.size().as_other());
207            rs.set_fill_color(Color::MAGENTA);
208            rs.set_scale(scale);
209            window.draw(&rs);
210            let mut s = Sprite::with_texture(&*tex);
211            s.set_scale(scale);
212            window.draw(&s);
213        }
214        window.display();
215    }
216    Ok(())
217}
examples/window-test.rs (line 41)
13fn main() -> SfResult<()> {
14    let configs = [
15        WindowConfig {
16            mode: (320, 240),
17            title: "(Windowed) Retro",
18            style: Style::CLOSE,
19        },
20        WindowConfig {
21            mode: (640, 480),
22            title: "(Windowed) Classic",
23            style: Style::DEFAULT,
24        },
25        WindowConfig {
26            mode: (800, 600),
27            title: "(Windowed) Big",
28            style: Style::TITLEBAR,
29        },
30    ];
31    let mut cfg_idx = 2usize;
32    let mut rw = RenderWindow::new(
33        configs[cfg_idx].mode,
34        "Window test",
35        Style::CLOSE,
36        &ContextSettings::default(),
37    )?;
38    let font = Font::from_memory_static(include_bytes!("resources/sansation.ttf"))?;
39    let fs_modes = VideoMode::fullscreen_modes();
40
41    while rw.is_open() {
42        while let Some(ev) = rw.poll_event() {
43            match ev {
44                Event::Closed => rw.close(),
45                Event::KeyPressed { code, .. } => match code {
46                    Key::Up => cfg_idx = cfg_idx.saturating_sub(1),
47                    Key::Down => {
48                        if cfg_idx + 1 < configs.len() + fs_modes.len() {
49                            cfg_idx += 1
50                        }
51                    }
52                    Key::Enter => match configs.get(cfg_idx) {
53                        Some(cfg) => {
54                            rw.recreate(cfg.mode, cfg.title, cfg.style, &ContextSettings::default())
55                        }
56                        None => match fs_modes.get(cfg_idx - configs.len()) {
57                            Some(mode) => rw.recreate(
58                                *mode,
59                                "Fullscreen",
60                                Style::FULLSCREEN,
61                                &ContextSettings::default(),
62                            ),
63                            None => {
64                                eprintln!("Invalid index: {cfg_idx}");
65                            }
66                        },
67                    },
68                    _ => {}
69                },
70                _ => {}
71            }
72        }
73        rw.clear(Color::BLACK);
74        let fontsize = 16;
75        let mut txt = Text::new("Arrow keys to select mode, enter to set.", &font, fontsize);
76        rw.draw(&txt);
77        let mut y = fontsize as f32;
78        for (i, cfg) in configs.iter().enumerate() {
79            let fc = if i == cfg_idx {
80                Color::YELLOW
81            } else {
82                Color::WHITE
83            };
84            txt.set_fill_color(fc);
85            txt.set_string(&format!(
86                "{}x{} \"{}\" ({:?})",
87                cfg.mode.0, cfg.mode.1, cfg.title, cfg.style
88            ));
89            txt.set_position((0., y));
90            rw.draw(&txt);
91            y += fontsize as f32;
92        }
93        let mut i = configs.len();
94        y += fontsize as f32;
95        txt.set_position((0., y));
96        txt.set_fill_color(Color::WHITE);
97        txt.set_string("= Fullscreen modes =");
98        rw.draw(&txt);
99        for mode in fs_modes.iter() {
100            let n_rows = 23;
101            let column = i / n_rows;
102            let row = i % n_rows;
103            let fc = if i == cfg_idx {
104                Color::YELLOW
105            } else {
106                Color::WHITE
107            };
108            txt.set_fill_color(fc);
109            let left_pad = 16.0;
110            let x = left_pad + (column * 128) as f32;
111            let gap = 16.0;
112            let y = y + gap + (row * fontsize as usize) as f32;
113            txt.set_position((x, y));
114            txt.set_string(&format!(
115                "{}x{}x{}",
116                mode.width, mode.height, mode.bits_per_pixel
117            ));
118            rw.draw(&txt);
119            i += 1;
120        }
121        rw.display();
122    }
123    Ok(())
124}
examples/positional-audio.rs (line 74)
46fn main() -> Result<(), Box<dyn Error>> {
47    example_ensure_right_working_dir();
48
49    let mut rw = RenderWindow::new(
50        (800, 600),
51        "Positional audio demo",
52        Style::CLOSE,
53        &Default::default(),
54    )?;
55    rw.set_vertical_sync_enabled(true);
56    let font = Font::from_file("sansation.ttf")?;
57    let mut text = Text::new("", &font, 20);
58    let mut music = match std::env::args().nth(1) {
59        Some(music_path) => Music::from_file(&music_path)?,
60        None => Music::from_file("canary.wav")?,
61    };
62    if music.channel_count() != 1 {
63        return Err("Sorry, only sounds with 1 channel are supported.".into());
64    };
65    music.set_looping(true);
66    music.play();
67    music.set_position(Vector3::new(0., 0., 0.));
68
69    let mut listener_pos = Vector3::new(0.0, 0.0, 0.0);
70    let center = Vector2::new(400., 300.);
71    let [mut go_left, mut go_right, mut go_up, mut go_down] = [false; 4];
72    let clock = Clock::start()?;
73
74    while rw.is_open() {
75        while let Some(ev) = rw.poll_event() {
76            match ev {
77                Event::Closed => rw.close(),
78                Event::KeyPressed { code, .. } => match code {
79                    Key::A => go_left = true,
80                    Key::D => go_right = true,
81                    Key::W => go_up = true,
82                    Key::S => go_down = true,
83                    _ => {}
84                },
85                Event::KeyReleased { code, .. } => match code {
86                    Key::A => go_left = false,
87                    Key::D => go_right = false,
88                    Key::W => go_up = false,
89                    Key::S => go_down = false,
90                    _ => {}
91                },
92                _ => {}
93            }
94        }
95        let Vector2f { x: mx, y: my } = rw.mouse_position().as_other();
96        let speed = 0.05;
97        if go_left {
98            listener_pos.x -= speed;
99        }
100        if go_right {
101            listener_pos.x += speed;
102        }
103        if go_up {
104            listener_pos.y -= speed;
105        }
106        if go_down {
107            listener_pos.y += speed;
108        }
109        let scale = 20.0; // Scale the positions for better visualization
110        listener::set_position(listener_pos);
111        listener::set_direction(Vector3::new(
112            (mx - center.x) / scale,
113            (my - center.y) / scale,
114            -1.,
115        ));
116        let Vector3 {
117            x: lx,
118            y: ly,
119            z: lz,
120        } = listener::position();
121        let Vector3 {
122            x: dx,
123            y: dy,
124            z: dz,
125        } = listener::direction();
126        rw.clear(Color::BLACK);
127        let mut circle_shape = CircleShape::new(8.0, 32);
128        // Draw circle at center, representing position of music being played
129        circle_shape.set_position(center);
130        circle_shape.set_fill_color(Color::YELLOW);
131        let t = clock.elapsed_time().as_seconds();
132        let radius = 12.0 + t.sin() * 3.0;
133        circle_shape.set_radius(radius);
134        circle_shape.set_origin(radius);
135        rw.draw(&circle_shape);
136        // Draw circle representing listener
137        circle_shape.set_position((center.x + lx * scale, center.y + ly * scale));
138        circle_shape.set_origin(4.0);
139        circle_shape.set_radius(4.0);
140        circle_shape.set_fill_color(Color::GREEN);
141        rw.draw(&circle_shape);
142        // Draw line from listener to direction vector position
143        rw.draw_line(
144            circle_shape.position(),
145            (center.x + dx * scale, center.y + dy * scale).into(),
146            2.0,
147        );
148        text.set_string("WASD + mouse for movement of listener");
149        text.set_position(0.);
150        rw.draw(&text);
151        text.set_string(&format!("Listener position: {lx}, {ly}, {lz}"));
152        text.set_position((0., 20.0));
153        rw.draw(&text);
154        text.set_string(&format!("Listener direction: {dx}, {dy}, {dz}"));
155        text.set_position((0., 40.0));
156        rw.draw(&text);
157        rw.display();
158    }
159    Ok(())
160}
examples/spritemark.rs (line 90)
62fn main() -> SfResult<()> {
63    example_ensure_right_working_dir();
64
65    let native_mode = VideoMode::desktop_mode();
66    let mut window = RenderWindow::new(
67        native_mode,
68        "Spritemark",
69        Style::default(),
70        &ContextSettings::default(),
71    )?;
72    window.set_position(Vector2::new(0, 0));
73    window.set_vertical_sync_enabled(true);
74    let font = Font::from_file("sansation.ttf")?;
75    let texture = Texture::from_file("devices.png")?;
76    let mut text = Text::new("", &font, 18);
77    text.set_outline_color(Color::BLACK);
78    text.set_outline_thickness(1.0);
79    let mut click_counter = 0;
80    let mut objects = Vec::new();
81    let mut rng = thread_rng();
82    let mut rs = RenderStates::default();
83    let mut buf = Vec::new();
84    let mut frames_rendered = 0;
85    let mut sec_clock = Clock::start()?;
86    let mut fps = 0;
87    let mut lmb_down = false;
88    let mut view = View::new()?;
89
90    while window.is_open() {
91        while let Some(event) = window.poll_event() {
92            match event {
93                Event::Closed
94                | Event::KeyPressed {
95                    code: Key::Escape, ..
96                } => window.close(),
97                Event::MouseButtonPressed {
98                    button: Button::Left,
99                    ..
100                } => {
101                    click_counter += 1;
102                    lmb_down = true;
103                }
104                Event::MouseButtonReleased {
105                    button: Button::Left,
106                    ..
107                } => {
108                    lmb_down = false;
109                }
110                Event::Resized { width, height } => {
111                    view.reset(Rect::new(0., 0., width as f32, height as f32));
112                    window.set_view(&view);
113                }
114                _ => {}
115            }
116        }
117
118        if lmb_down {
119            let mp = window.mouse_position();
120            for _ in 0..25 {
121                objects.push(Object {
122                    position: fconv(mp),
123                    speed: Vector2f::new(rng.gen_range(-3.0..3.0), 0.0),
124                    image_id: click_counter % N_IMAGES,
125                    angle: 0.0,
126                    rot_speed: rng.gen_range(-2.0..2.0),
127                });
128            }
129        }
130
131        for obj in &mut objects {
132            let size = f32::from(SUBIMAGE_SIZE);
133            let tex_x = f32::from(obj.image_id) * size;
134            let mut tf = Transform::default();
135            tf.translate(obj.position.x, obj.position.y);
136            tf.rotate_with_center(obj.angle, size / 2.0, size / 2.0);
137            buf.push(Vertex {
138                color: Color::WHITE,
139                position: tf.transform_point(Vector2f::new(0., 0.)),
140                tex_coords: Vector2f::new(tex_x, 0.),
141            });
142            buf.push(Vertex {
143                color: Color::WHITE,
144                position: tf.transform_point(Vector2f::new(0., size)),
145                tex_coords: Vector2f::new(tex_x, size),
146            });
147            buf.push(Vertex {
148                color: Color::WHITE,
149                position: tf.transform_point(Vector2f::new(size, size)),
150                tex_coords: Vector2f::new(tex_x + size, size),
151            });
152            buf.push(Vertex {
153                color: Color::WHITE,
154                position: tf.transform_point(Vector2f::new(size, 0.)),
155                tex_coords: Vector2f::new(tex_x + size, 0.),
156            });
157            obj.update(window.size().y as f32, window.size().x as f32);
158        }
159        window.clear(Color::BLACK);
160        rs.texture = Some(&texture);
161        window.draw_primitives(&buf, PrimitiveType::QUADS, &rs);
162        rs.texture = None;
163        text.set_string(&format!("{} sprites\n{fps} fps", objects.len()));
164        window.draw_text(&text, &rs);
165        window.display();
166        buf.clear();
167        frames_rendered += 1;
168        if sec_clock.elapsed_time().as_milliseconds() >= 1000 {
169            fps = frames_rendered;
170            sec_clock.restart();
171            frames_rendered = 0;
172        }
173    }
174    Ok(())
175}
Source

pub fn set_title<S: SfStrConv>(&mut self, title: S)

Change the title of a window

§Arguments
  • title - New title
Source

pub fn set_visible(&mut self, visible: bool)

Show or hide a window.

§Arguments
  • visible - true to show the window, false to hide it
Source

pub fn position(&self) -> Vector2i

Get the position of a window

Return the position in pixels

Source

pub fn set_position(&mut self, position: Vector2i)

Change the position of a window on screen

This function only works for top-level windows (i.e. it will be ignored for windows created from the handle of a child window/control).

§Arguments
  • position - New position of the window, in pixels
Examples found in repository?
examples/spritemark.rs (line 72)
62fn main() -> SfResult<()> {
63    example_ensure_right_working_dir();
64
65    let native_mode = VideoMode::desktop_mode();
66    let mut window = RenderWindow::new(
67        native_mode,
68        "Spritemark",
69        Style::default(),
70        &ContextSettings::default(),
71    )?;
72    window.set_position(Vector2::new(0, 0));
73    window.set_vertical_sync_enabled(true);
74    let font = Font::from_file("sansation.ttf")?;
75    let texture = Texture::from_file("devices.png")?;
76    let mut text = Text::new("", &font, 18);
77    text.set_outline_color(Color::BLACK);
78    text.set_outline_thickness(1.0);
79    let mut click_counter = 0;
80    let mut objects = Vec::new();
81    let mut rng = thread_rng();
82    let mut rs = RenderStates::default();
83    let mut buf = Vec::new();
84    let mut frames_rendered = 0;
85    let mut sec_clock = Clock::start()?;
86    let mut fps = 0;
87    let mut lmb_down = false;
88    let mut view = View::new()?;
89
90    while window.is_open() {
91        while let Some(event) = window.poll_event() {
92            match event {
93                Event::Closed
94                | Event::KeyPressed {
95                    code: Key::Escape, ..
96                } => window.close(),
97                Event::MouseButtonPressed {
98                    button: Button::Left,
99                    ..
100                } => {
101                    click_counter += 1;
102                    lmb_down = true;
103                }
104                Event::MouseButtonReleased {
105                    button: Button::Left,
106                    ..
107                } => {
108                    lmb_down = false;
109                }
110                Event::Resized { width, height } => {
111                    view.reset(Rect::new(0., 0., width as f32, height as f32));
112                    window.set_view(&view);
113                }
114                _ => {}
115            }
116        }
117
118        if lmb_down {
119            let mp = window.mouse_position();
120            for _ in 0..25 {
121                objects.push(Object {
122                    position: fconv(mp),
123                    speed: Vector2f::new(rng.gen_range(-3.0..3.0), 0.0),
124                    image_id: click_counter % N_IMAGES,
125                    angle: 0.0,
126                    rot_speed: rng.gen_range(-2.0..2.0),
127                });
128            }
129        }
130
131        for obj in &mut objects {
132            let size = f32::from(SUBIMAGE_SIZE);
133            let tex_x = f32::from(obj.image_id) * size;
134            let mut tf = Transform::default();
135            tf.translate(obj.position.x, obj.position.y);
136            tf.rotate_with_center(obj.angle, size / 2.0, size / 2.0);
137            buf.push(Vertex {
138                color: Color::WHITE,
139                position: tf.transform_point(Vector2f::new(0., 0.)),
140                tex_coords: Vector2f::new(tex_x, 0.),
141            });
142            buf.push(Vertex {
143                color: Color::WHITE,
144                position: tf.transform_point(Vector2f::new(0., size)),
145                tex_coords: Vector2f::new(tex_x, size),
146            });
147            buf.push(Vertex {
148                color: Color::WHITE,
149                position: tf.transform_point(Vector2f::new(size, size)),
150                tex_coords: Vector2f::new(tex_x + size, size),
151            });
152            buf.push(Vertex {
153                color: Color::WHITE,
154                position: tf.transform_point(Vector2f::new(size, 0.)),
155                tex_coords: Vector2f::new(tex_x + size, 0.),
156            });
157            obj.update(window.size().y as f32, window.size().x as f32);
158        }
159        window.clear(Color::BLACK);
160        rs.texture = Some(&texture);
161        window.draw_primitives(&buf, PrimitiveType::QUADS, &rs);
162        rs.texture = None;
163        text.set_string(&format!("{} sprites\n{fps} fps", objects.len()));
164        window.draw_text(&text, &rs);
165        window.display();
166        buf.clear();
167        frames_rendered += 1;
168        if sec_clock.elapsed_time().as_milliseconds() >= 1000 {
169            fps = frames_rendered;
170            sec_clock.restart();
171            frames_rendered = 0;
172        }
173    }
174    Ok(())
175}
Source

pub fn set_size<S: Into<Vector2u>>(&mut self, size: S)

Change the size of the rendering region of a window

§Arguments
  • size - New size, in pixels
Source

pub unsafe fn set_mouse_cursor(&mut self, cursor: &Cursor)

Set the displayed cursor to a native system cursor.

Upon window creation, the arrow cursor is used by default.

§Safety

The cursor can not be destroyed while in use by the window.

Examples found in repository?
examples/cursor.rs (line 137)
72fn main() -> SfResult<()> {
73    example_ensure_right_working_dir();
74
75    let mut cursor = Cursor::from_system(CursorType::Arrow)?;
76    let mut rw = RenderWindow::new(
77        (800, 800),
78        "SFML cursor example",
79        Style::CLOSE,
80        &ContextSettings::default(),
81    )?;
82    rw.set_vertical_sync_enabled(true);
83    let font = Font::from_file("sansation.ttf")?;
84    let mut failed_index = usize::MAX;
85    let mut selected_index = usize::MAX;
86    let set_button = Rect::new(348, 500, 100, 32);
87    let hotspot_button = Rect::new(458, 500, 100, 32);
88    let clear_button = Rect::new(568, 500, 100, 32);
89    let mut pixel_grid = [false; DRAW_GRID_WH as usize * DRAW_GRID_WH as usize];
90    let mut hotspot_selection = false;
91    let mut hotspot_selected = false;
92    let mut hotspot = Vector2::new(8, 8);
93    let mut modif = false;
94
95    let mut buttons = Vec::new();
96    let cursor_types = [
97        CursorType::Arrow,
98        CursorType::ArrowWait,
99        CursorType::Wait,
100        CursorType::Text,
101        CursorType::Hand,
102        CursorType::SizeHorizontal,
103        CursorType::SizeVertical,
104        CursorType::SizeTopLeftBottomRight,
105        CursorType::SizeBottomLeftTopRight,
106        CursorType::SizeLeft,
107        CursorType::SizeRight,
108        CursorType::SizeTop,
109        CursorType::SizeBottom,
110        CursorType::SizeTopLeft,
111        CursorType::SizeBottomRight,
112        CursorType::SizeBottomLeft,
113        CursorType::SizeTopRight,
114        CursorType::SizeAll,
115        CursorType::Cross,
116        CursorType::Help,
117        CursorType::NotAllowed,
118    ];
119    for i in 0..cursor_types.len() {
120        buttons.push(Rect::new(16, 16 + i as i32 * 36, 250, 32));
121    }
122
123    while rw.is_open() {
124        while let Some(ev) = rw.poll_event() {
125            match ev {
126                Event::Closed => rw.close(),
127                Event::MouseButtonPressed {
128                    button: mouse::Button::Left,
129                    x,
130                    y,
131                } => {
132                    for (i, b) in buttons.iter().enumerate() {
133                        if mouse_over(b, x, y) {
134                            match cursor.load_from_system(cursor_types[i]) {
135                                Ok(()) => {
136                                    unsafe {
137                                        rw.set_mouse_cursor(&cursor);
138                                    }
139                                    selected_index = i;
140                                }
141                                Err(e) => {
142                                    eprintln!("{e}");
143                                    failed_index = i;
144                                }
145                            }
146                        }
147                    }
148                    if mouse_over(&set_button, x, y) {
149                        let mut pixels = [0; DRAW_GRID_WH as usize * DRAW_GRID_WH as usize * 4];
150                        for (i, px) in pixel_grid.iter().enumerate() {
151                            let offset = i * 4;
152                            if *px {
153                                pixels[offset] = 255;
154                                pixels[offset + 1] = 255;
155                                pixels[offset + 2] = 255;
156                                pixels[offset + 3] = 255;
157                            }
158                        }
159                        unsafe {
160                            match cursor.load_from_pixels(
161                                &pixels,
162                                Vector2::new(DRAW_GRID_WH as u32, DRAW_GRID_WH as u32),
163                                hotspot,
164                            ) {
165                                Ok(()) => {
166                                    rw.set_mouse_cursor(&cursor);
167                                }
168                                Err(e) => {
169                                    eprintln!("{e}");
170                                }
171                            }
172                        }
173                        modif = false;
174                    }
175                    if mouse_over(&clear_button, x, y) {
176                        for px in pixel_grid.iter_mut() {
177                            *px = false;
178                        }
179                        modif = true;
180                    }
181                    if mouse_over(&hotspot_button, x, y) {
182                        hotspot_selection = true;
183                    }
184                }
185                Event::MouseButtonReleased {
186                    button: mouse::Button::Left,
187                    ..
188                } => {
189                    if hotspot_selected {
190                        hotspot_selection = false;
191                        hotspot_selected = false;
192                    }
193                }
194                _ => {}
195            }
196        }
197        let mut set_button_highlighted = false;
198        let mut hotspot_button_highlighted = false;
199        let mut clear_button_highlighted = false;
200        // System cursor set button interactions
201        let mp = rw.mouse_position();
202        let mut highlight_index = usize::MAX;
203        for (i, b) in buttons.iter().enumerate() {
204            if mouse_over(b, mp.x, mp.y) {
205                highlight_index = i;
206            }
207        }
208        if mouse_over(&set_button, mp.x, mp.y) {
209            set_button_highlighted = true;
210        }
211        if mouse_over(&hotspot_button, mp.x, mp.y) {
212            hotspot_button_highlighted = true;
213        }
214        if mouse_over(&clear_button, mp.x, mp.y) {
215            clear_button_highlighted = true;
216        }
217        // Grid interactions
218        let rela_x = mp.x - DRAW_AREA_TOPLEFT.0 as i32;
219        let rela_y = mp.y - DRAW_AREA_TOPLEFT.1 as i32;
220        let (gx, gy) = (rela_x / DRAW_CELL_WH as i32, rela_y / DRAW_CELL_WH as i32);
221        if gx >= 0 && gy >= 0 {
222            if let Some(cell) = gridindex(&mut pixel_grid, gx as usize, gy as usize) {
223                if hotspot_selection {
224                    hotspot_selected = true;
225                    hotspot = Vector2::new(gx as u32, gy as u32);
226                    modif = true;
227                } else if mouse::Button::Left.is_pressed() {
228                    *cell = true;
229                    modif = true;
230                } else if mouse::Button::Right.is_pressed() {
231                    *cell = false;
232                    modif = true;
233                }
234            }
235        }
236        rw.clear(Color::BLACK);
237        // Draw system cursor set buttons
238        let mut shape = RectangleShape::default();
239        let mut text = Text::new("", &font, 14);
240        shape.set_outline_thickness(-1.0);
241        shape.set_outline_color(Color::WHITE);
242        for (i, b) in buttons.iter().enumerate() {
243            let types = [
244                "ARROW",
245                "ARROW_WAIT",
246                "WAIT",
247                "TEXT",
248                "HAND",
249                "SIZE_HORIZONTAL",
250                "SIZE_VERTICAL",
251                "SIZE_TOP_LEFT_BOTTOM_RIGHT",
252                "SIZE_BOTTOM_LEFT_TOP_RIGHT",
253                "SIZE_LEFT",
254                "SIZE_RIGHT",
255                "SIZE_TOP",
256                "SIZE_BOTTOM",
257                "SIZE_TOP_LEFT",
258                "SIZE_BOTTOM_RIGHT",
259                "SIZE_BOTTOM_LEFT",
260                "SIZE_TOP_RIGHT",
261                "SIZE_ALL",
262                "CROSS",
263                "HELP",
264                "NOT_ALLOWED",
265            ];
266            draw_button(
267                b,
268                &mut shape,
269                &mut text,
270                types[i],
271                &mut rw,
272                bstyle(highlight_index == i, selected_index == i, failed_index == i),
273            );
274        }
275        // Draw pixel drawing grid
276        shape.set_fill_color(Color::TRANSPARENT);
277        for y in 0..DRAW_GRID_WH {
278            for x in 0..DRAW_GRID_WH {
279                if hotspot.x == x as u32 && hotspot.y == y as u32 {
280                    shape.set_outline_color(Color::RED);
281                } else {
282                    shape.set_outline_color(Color::rgb(180, 180, 180));
283                }
284                if gridindex(&mut pixel_grid, x as usize, y as usize).is_some_and(|bool| *bool) {
285                    shape.set_fill_color(Color::WHITE);
286                } else {
287                    shape.set_fill_color(Color::TRANSPARENT);
288                }
289                shape.set_size((DRAW_CELL_WH as f32, DRAW_CELL_WH as f32));
290                shape.set_position((
291                    DRAW_AREA_TOPLEFT.0 as f32 + (x as f32 * DRAW_CELL_WH as f32),
292                    DRAW_AREA_TOPLEFT.1 as f32 + (y as f32 * DRAW_CELL_WH as f32),
293                ));
294                rw.draw(&shape);
295            }
296        }
297        draw_button(
298            &set_button,
299            &mut shape,
300            &mut text,
301            if modif { "Set*" } else { "Set" },
302            &mut rw,
303            bstyle(set_button_highlighted, false, false),
304        );
305        draw_button(
306            &hotspot_button,
307            &mut shape,
308            &mut text,
309            "Hotspot",
310            &mut rw,
311            bstyle(hotspot_button_highlighted, hotspot_selection, false),
312        );
313        draw_button(
314            &clear_button,
315            &mut shape,
316            &mut text,
317            "Clear",
318            &mut rw,
319            bstyle(clear_button_highlighted, false, false),
320        );
321        rw.display();
322    }
323    Ok(())
324}
Source

pub fn has_focus(&self) -> bool

Check whether the window has the input focus.

At any given time, only one window may have the input focus to receive input events such as keystrokes or most mouse events.

Source

pub fn request_focus(&mut self)

Request the current window to be made the active foreground window.

At any given time, only one window may have the input focus to receive input events such as keystrokes or mouse events. If a window requests focus, it only hints to the operating system, that it would like to be focused. The operating system is free to deny the request. This is not to be confused with RenderWindow::set_active.

Source§

impl RenderWindow

System integration

Source

pub fn system_handle(&self) -> Handle

Get the OS-specific handle of the window.

The type of the returned handle is Handle, which is a typedef to the handle type defined by the OS. You shouldn’t need to use this function, unless you have very specific stuff to implement that SFML doesn’t support, or implement a temporary workaround until a bug is fixed.

Trait Implementations§

Source§

impl Debug for RenderWindow

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for RenderWindow

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl RenderTarget for RenderWindow

Source§

fn push_gl_states(&mut self)

Save the current OpenGL render states and matrices Read more
Source§

fn pop_gl_states(&mut self)

Restore the previously saved OpenGL render states and matrices
Source§

fn reset_gl_states(&mut self)

Reset the internal OpenGL states so that the target is ready for drawing Read more
Source§

fn set_view(&mut self, view: &View)

set a new view to the target
Source§

fn view(&self) -> &View

return the current view
Source§

fn default_view(&self) -> &View

get the default view for the render target
Source§

fn map_pixel_to_coords(&self, point: Vector2i, view: &View) -> Vector2f

Convert a point from window coordinates to world coordinates Read more
Source§

fn map_pixel_to_coords_current_view(&self, point: Vector2i) -> Vector2f

Convert a point from window coordinates to world coordinates Read more
Source§

fn map_coords_to_pixel(&self, point: Vector2f, view: &View) -> Vector2i

Convert a point from world coordinates to window coordinates Read more
Source§

fn map_coords_to_pixel_current_view(&self, point: Vector2f) -> Vector2i

Convert a point from window coordinates to world coordinates Read more
Source§

fn viewport(&self, view: &View) -> IntRect

get the viewport of the render target
Source§

fn size(&self) -> Vector2u

Get the size of the rendering region of a window Read more
Source§

fn draw(&mut self, object: &dyn Drawable)

Draw a drawable object to the render target Read more
Source§

fn draw_with_renderstates( &mut self, object: &dyn Drawable, render_states: &RenderStates<'_, '_, '_>, )

Draw a drawable object to the render-target with a RenderStates Read more
Source§

fn draw_text( &mut self, text: &Text<'_>, render_states: &RenderStates<'_, '_, '_>, )

Draw Text
Source§

fn draw_rc_text( &mut self, text: &RcText, render_states: &RenderStates<'_, '_, '_>, )

Draw RcText
Source§

fn draw_shape( &mut self, shape: &CustomShape<'_>, render_states: &RenderStates<'_, '_, '_>, )

Draw Shape
Source§

fn draw_sprite( &mut self, sprite: &Sprite<'_>, render_states: &RenderStates<'_, '_, '_>, )

Draw Sprite
Source§

fn draw_rc_sprite( &mut self, sprite: &RcSprite, render_states: &RenderStates<'_, '_, '_>, )

Draw RcSprite
Source§

fn draw_circle_shape( &mut self, circle_shape: &CircleShape<'_>, render_states: &RenderStates<'_, '_, '_>, )

Draw CircleShape
Source§

fn draw_rectangle_shape( &mut self, rectangle_shape: &RectangleShape<'_>, render_states: &RenderStates<'_, '_, '_>, )

Draw RectangleShape
Source§

fn draw_convex_shape( &mut self, convex_shape: &ConvexShape<'_>, render_states: &RenderStates<'_, '_, '_>, )

Draw ConvexShape
Source§

fn draw_vertex_buffer( &mut self, vertex_buffer: &VertexBuffer, render_states: &RenderStates<'_, '_, '_>, )

Draw primitives defined by a vertex buffer
Source§

fn draw_primitives( &mut self, vertices: &[Vertex], ty: PrimitiveType, rs: &RenderStates<'_, '_, '_>, )

Draw primitives defined by an array of vertices.
Source§

fn clear(&mut self, color: Color)

clear the screen

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

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