pushrod/render/texture_store.rs
1// Pushrod Rendering Library
2// Texture Store
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use sdl2::render::{Canvas, Texture};
17use sdl2::video::Window;
18
19/// This is a store used by the `TextureStore`.
20#[derive(Default)]
21pub struct TextureStore {
22 store: Option<Texture>,
23 width: u32,
24 height: u32,
25}
26
27/// This is a `TextureStore` that is used by `Widget`s to draw against. It serves as a GPU-based
28/// `Texture` store that can be changed at any time during the drawing loop.
29impl TextureStore {
30 /// Retrieves a `&mut Texture` reference to the stored `Texture` object.
31 ///
32 /// Example use:
33 /// ```rust,no_run
34 /// c.with_texture_canvas(texture_store.get_mut_ref(), |texture| {
35 /// texture.set_draw_color(base_color);
36 /// texture.clear();
37 ///
38 /// texture.set_draw_color(border_color);
39 /// texture
40 /// .draw_rect(Rect::new(0, 0, 200, 200))
41 /// .unwrap();
42 /// })
43 /// .unwrap();
44 /// ```
45 pub fn get_mut_ref(&mut self) -> &mut Texture {
46 self.store.as_mut().unwrap()
47 }
48
49 /// Retrieves a `Option<&Texture>` object for the `Texture` object store. Use this as a shortcut
50 /// to the `Widget`'s return values (see `BaseWidget` for reference.)
51 pub fn get_optional_ref(&mut self) -> Option<&Texture> {
52 Some(self.store.as_ref().unwrap())
53 }
54
55 /// This is used to create a new `Texture` object that can be drawn against. If the `Widget` is
56 /// ever redrawn, this function will automatically generate a new `Texture` to draw against, and
57 /// destroy the previously stored `Texture`. If any changes are observed when calling this
58 /// function (ie. the width changes, height changes, or the store is lost), it is regenerated.
59 pub fn create_or_resize_texture(&mut self, c: &mut Canvas<Window>, width: u32, height: u32) {
60 if self.store.is_none() || self.width != width || self.height != height {
61 self.width = width;
62 self.height = height;
63 self.store = Some(c.create_texture_target(None, width, height).unwrap());
64
65 eprintln!("Created texture: size={}x{}", width, height);
66 }
67 }
68}