lambda_platform/gfx/
viewport.rs

1//! viewport.rs - Low level viewport management for the render context.
2
3/// Viewport is a rectangle that defines the area of the screen that will be
4/// rendered to. For instance, if the viewport is set to x=0, y=0, width=100,
5/// height=100, then only the top left 100x100 pixels of the screen will be
6/// rendered to.
7#[derive(Debug, Clone, PartialEq)]
8pub struct ViewPort {
9  viewport: gfx_hal::pso::Viewport,
10}
11
12impl ViewPort {
13  /// Get the internal viewport object.
14  pub(super) fn internal_viewport(&self) -> gfx_hal::pso::Viewport {
15    return self.viewport.clone();
16  }
17}
18
19/// A builder for `Viewport`.
20pub struct ViewPortBuilder {
21  x: i16,
22  y: i16,
23}
24
25impl ViewPortBuilder {
26  /// Create a new `ViewportBuilder`.
27  pub fn new() -> Self {
28    return ViewPortBuilder { x: 0, y: 0 };
29  }
30
31  /// Specify a viewport with specific coordinates
32  pub fn with_coordinates(mut self, x: i16, y: i16) -> Self {
33    self.x = x;
34    self.y = y;
35    return self;
36  }
37
38  /// Build a viewport to use for viewing an entire surface.
39  pub fn build(self, width: u32, height: u32) -> ViewPort {
40    // The viewport currently renders to the entire size of the surface. and has
41    // a non-configurable depth
42    return ViewPort {
43      viewport: gfx_hal::pso::Viewport {
44        rect: gfx_hal::pso::Rect {
45          x: self.x,
46          y: self.y,
47          w: width as i16,
48          h: height as i16,
49        },
50        depth: 0.0..1.0,
51      },
52    };
53  }
54}
55
56#[cfg(test)]
57pub mod tests {
58  /// Test the viewport builder in it's default state.
59  #[test]
60  fn viewport_builder_default_initial_state() {
61    let viewport_builder = super::ViewPortBuilder::new();
62    assert_eq!(viewport_builder.x, 0);
63    assert_eq!(viewport_builder.y, 0);
64  }
65
66  /// Test that the viewport builder can be configured with specific
67  /// coordinates.
68  #[test]
69  fn viewport_builder_with_coordinates() {
70    let viewport_builder =
71      super::ViewPortBuilder::new().with_coordinates(10, 10);
72    assert_eq!(viewport_builder.x, 10);
73    assert_eq!(viewport_builder.y, 10);
74  }
75
76  #[test]
77  fn viewport_builder_builds_successfully() {
78    let viewport_builder =
79      super::ViewPortBuilder::new().with_coordinates(10, 10);
80    let viewport = viewport_builder.build(100, 100);
81    assert_eq!(viewport.viewport.rect.x, 10);
82    assert_eq!(viewport.viewport.rect.y, 10);
83    assert_eq!(viewport.viewport.rect.w, 100);
84    assert_eq!(viewport.viewport.rect.h, 100);
85  }
86}