# core/viewmanager (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/core/viewmanager/

View manager.
- canvas_native_size:	Logical size of the window interior. (physical pixels / scale)
- canvas_pixel_size:	Actual rendering pixel size of the window interior. (drawing buffer)
- view_native_rect:	The view area actually used. (a sub-area relative to canvas_native_size)
- view_size:			The view size actually used. (size of the coordinate system the scene draws in)
- The original's device_pixel_ratio is the window's scale factor.
- Render scale limit (set_max_render_pixel_ratio): as in the original, only the value is stored (nothing happens for the same value) and is_view_rect_pending is raised.
  At the start of the next frame it refits with the limited scale through the same path as a window resize (Engine::resize), and calculate_view_rect lowers it.
  (Changing the canvas size in the middle of a frame makes that frame black) The web shrinks the canvas drawing buffer,
  and desktop draws at the reduced size in the bottom-left of the default framebuffer, then stretches it to the window size. (platform/desktop/renderscaler.rs)
- Safe area insets (get_safe_area_insets, set_safe_area_override) are SafeAreaInsets with named fields like the original { top, right, bottom, left }.
  The address's ?safeArea=top,right,bottom,left corresponds on desktop to the environment variable VANILLA_SAFE_AREA=top,right,bottom,left.
  CSS env(safe-area-inset-*) is read on the web and is 0 on desktop. Chrome desktop is 0 too. (nonzero values only come in on Android, platform/desktop.rs read_safe_area_insets)
  set_safe_area_override takes effect on both.
- get_client_native_size: the whole page size (window.innerWidth, innerHeight) as in the original. Desktop has no page, so it is the logical size of the window interior.
- convert_client_to_view: screen (client) coordinates to view coordinates. The web subtracts the canvas's current position, and on desktop the window's logical coordinates are the client coordinates.
- Safe area sides to ignore (set_ignored_safe_area_sides) are taken as the SafeAreaSide enum instead of the original's strings like "top".
- The canvas CSS height in get_css_pixel_scale is canvas_native_size.y. (the canvas's CSS height on the web, the window's logical height on desktop)
- apply_aspect_view_scale_mode measures the ratio with the canvas logical size. (the original uses the window interior size if the canvas size is 0.
  In the Rust version the platform fits the canvas size before the scene runs, so when it is 0 the window is 0 too)

## SafeAreaInsets (struct) (Clone, Copy, Debug, Default, PartialEq)

Safe area insets. (the original { top, right, bottom, left })
- CSS pixels when passed to set_safe_area_override, view coordinates when returned by get_safe_area_insets.

Example: Read a forced value that mimics a notch in view coordinates

```rust
use vanilla::{SafeAreaInsets, Vector2, ViewManager, ViewScaleMode};

let mut view_manager = ViewManager::new(Vector2::create(1280.0, 720.0), ViewScaleMode::StretchShort);
view_manager.calculate_view_rect(1280, 720, 2.0);
view_manager.set_safe_area_override(Some(SafeAreaInsets::create(44.0, 0.0, 34.0, 0.0)));
let insets = view_manager.get_safe_area_insets();
assert_eq!(insets, SafeAreaInsets::create(88.0, 0.0, 68.0, 0.0));
assert_eq!(insets.top, 88.0);
```

- `pub top: f64` (field, since 0.4.0): Top inset.
  - returns f64
- `pub right: f64` (field, since 0.4.0): Right inset.
  - returns f64
- `pub bottom: f64` (field, since 0.4.0): Bottom inset.
  - returns f64
- `pub left: f64` (field, since 0.4.0): Left inset.
  - returns f64
- `pub const fn create(top: f64, right: f64, bottom: f64, left: f64) -> SafeAreaInsets` (static, since 0.4.0): Creates. (in the order of the original { top, right, bottom, left })
  - `top` f64: Top inset.
  - `right` f64: Right inset.
  - `bottom` f64: Bottom inset.
  - `left` f64: Left inset.
  - returns SafeAreaInsets: Insets with all four sides filled.

## ViewManager (struct)

View manager. (computes the view area the scene draws from the window size, scale, reference resolution and view scale mode, held by the engine)

Example: Fit a 1280x720 reference resolution to the short axis of a 1600x720 window

```rust
use vanilla::{Rect, Vector2, ViewManager, ViewScaleMode};

let mut view_manager = ViewManager::new(Vector2::create(1280.0, 720.0), ViewScaleMode::StretchShort);
view_manager.calculate_view_rect(1600, 720, 1.0);
assert_eq!(view_manager.get_canvas_native_size(), Vector2::create(1600.0, 720.0));
assert_eq!(view_manager.get_view_size(), Vector2::create(1280.0, 720.0));
assert_eq!(view_manager.get_view_native_rect(), Rect::create(160.0, 0.0, 1280.0, 720.0));
assert_eq!(view_manager.get_target_resolution_scale(), 1.0);
assert_eq!(view_manager.canvas_position_to_view_position(Vector2::create(160.0, 0.0)), Vector2::zero());
```

Example: Read the view size in a scene

```rust
use vanilla::{Engine, Vector2};

fn read_view_center(engine: &Engine) -> Vector2 {
	let view_size = engine.get_view_manager().get_view_size();
	Vector2::create(view_size.x * 0.5, view_size.y * 0.5)
}
```

- `pub fn new(reference_resolution_size: Vector2, view_scale_mode: ViewScaleMode) -> ViewManager` (constructor, since 0.3.2): Constructor.
  - `reference_resolution_size` Vector2: Reference resolution. (size of the coordinate system the scene draws in, pixels)
  - `view_scale_mode` ViewScaleMode: View scale mode.
  - returns ViewManager: New view manager. (scale 1, size and view area 0, the view area appears only after calling calculate_view_rect)
- `pub fn calculate_view_rect(&mut self, physical_width: u32, physical_height: u32, scale_factor: f64)` (method, since 0.3.2): Computes the view area. (called by the engine when the window size or scale changes)
  - The logical size inside the window is the physical pixels divided by the scale, rounded.
  - `physical_width` u32: Inner width of the window. (physical pixels)
  - `physical_height` u32: Inner height of the window. (physical pixels)
  - `scale_factor` f64: Window scale factor. (the original devicePixelRatio, 1 if 0 or less)

  Example: A mode that fits the width and expands the height in a scale 2 window

  ```rust
  use vanilla::{Vector2, ViewManager, ViewScaleMode};
  
  let mut view_manager = ViewManager::new(Vector2::create(1280.0, 720.0), ViewScaleMode::StretchWidthExpandHeight);
  view_manager.calculate_view_rect(1500, 2000, 2.0);
  assert_eq!(view_manager.get_canvas_native_size(), Vector2::create(750.0, 1000.0));
  assert_eq!(view_manager.get_view_size(), Vector2::create(1280.0, 1707.0));
  ```

- `pub fn apply_transform(&self, graphic: &mut Graphic, scale_x: f64, scale_y: f64, skew_x: f64, skew_y: f64, translate_x: f64, translate_y: f64)` (method, since 0.3.2): Applies the coordinate system.
  - Same as graphic.set_transform(scale_x, skew_y, skew_x, scale_y, translate_x, translate_y). (Canvas2D order a, b, c, d, e, f)
  - `graphic` &mut Graphic: Graphic to set the coordinate system on.
  - `scale_x` f64: Horizontal scale. (matrix a)
  - `scale_y` f64: Vertical scale. (matrix d)
  - `skew_x` f64: Horizontal skew. (matrix c)
  - `skew_y` f64: Vertical skew. (matrix b)
  - `translate_x` f64: Horizontal translation. (drawing buffer pixels, matrix e)
  - `translate_y` f64: Vertical translation. (drawing buffer pixels, matrix f)
- `pub fn apply_canvas_native_rect(&self, graphic: &mut Graphic)` (method, since 0.3.2): Applies the full screen area. (coordinate unit = canvas_native_size)
  - `graphic` &mut Graphic: Graphic to set the coordinate system on.
- `pub fn apply_view_rect(&self, graphic: &mut Graphic)` (method, since 0.3.2): Applies the view area. (coordinate unit = get_view_size(), draws with the same code regardless of mode)
  - `graphic` &mut Graphic: Graphic to set the coordinate system on.
- `pub fn apply_reference_resolution_size(&mut self, reference_resolution_size: Vector2)` (method, since 0.3.2): Resets the reference resolution.
  - The view area changes from the next calculate_view_rect.
  - `reference_resolution_size` Vector2: New reference resolution. (pixels)
- `pub fn get_device_pixel_ratio(&self) -> f64` (method, since 0.3.2): Scale factor. (the original devicePixelRatio)
  - returns f64: Scale of the window. (the value passed to calculate_view_rect, 1 if it was 0 or less, initially 1)
- `pub fn set_view_scale_mode(&mut self, view_scale_mode: ViewScaleMode)` (method, since 0.3.2): Sets the view scale mode. (applied from the next calculate_view_rect)
  - `view_scale_mode` ViewScaleMode: New view scale mode.
- `pub fn get_view_scale_mode(&self) -> ViewScaleMode` (method, since 0.3.2): Returns the view scale mode.
  - returns ViewScaleMode: Current view scale mode.
- `pub fn get_client_native_size(&self) -> Vector2` (method, since 0.4.0): Full page size. (the original window.innerWidth, innerHeight, the logical inner window size on desktop)
  - returns Vector2: Logical size of the whole page. (0 before calculate_view_rect)
- `pub fn get_canvas_native_size(&self) -> Vector2` (method, since 0.3.2): Logical inner window size.
  - returns Vector2: Inner window size. (logical pixels, physical pixels / scale rounded, 0 before calculate_view_rect)
- `pub fn get_canvas_pixel_size(&self) -> Vector2` (method, since 0.3.2): Inner window size in physical pixels.
  - returns Vector2: Drawing buffer size. (physical pixels, the value passed to calculate_view_rect)
- `pub fn get_reference_resolution_size(&self) -> Vector2` (method, since 0.3.2): Reference resolution.
  - returns Vector2: Reference resolution. (pixels)
- `pub fn get_view_size(&self) -> Vector2` (method, since 0.3.2): View size.
  - returns Vector2: Size of the coordinate system the scene draws in. (the logical inner window size in None mode, a size computed from the window ratio in ExpandHeight, ExpandWidth and ExpandLong, otherwise the reference resolution)
- `pub fn get_view_native_rect(&self) -> Rect` (method, since 0.3.2): View area. (logical inner window coordinates)
  - returns Rect: Area the view takes up inside the window. (logical pixels, leftover margins are outside the area)
- `pub fn get_target_resolution_scale(&self) -> f64` (method, since 0.3.2): Reference resolution → screen scale.
  - returns f64: How many logical inner window pixels one view unit is. (1 in None and ReferenceResolution modes)
- `pub fn get_css_pixel_scale(&self) -> f64` (method, since 0.4.0): How many CSS pixels one view unit is on screen. (CSS height of the canvas / view height, 1 if it cannot be measured)
  - The fixed side of the view is always the same length, so on a small screen (a portal's PC iframe and so on) one unit becomes much smaller than 1 CSS pixel and text becomes unreadable.
    Used to compute a scale that enlarges only the UI layer. (e.g. minimum CSS scale / this value)
  - returns f64: Logical inner window height / view height. (1 if either is 0 or less)
- `pub fn set_max_render_pixel_ratio(&mut self, max_render_pixel_ratio: f64)` (method, since 0.4.0): Sets the maximum render pixel ratio. (Keeps the canvas from growing too large on high-DPI devices, 0 means no limit)
  - Does nothing for the same value. When it changes, only the value is stored and is_view_rect_pending is raised.
  - The canvas size is fitted at the head of the next frame through the same path as a window resize (Engine::resize). (Scenes also receive the changed screen area)
    Changing the canvas size in the middle of a frame (tick, draw) clears the drawing buffer, and that frame is drawn with the viewport set earlier, so one frame turned black.
  - The web shrinks the canvas drawing buffer; the desktop draws at the size reduced by that ratio and stretches it to the window size at the end of the frame. (desktop/renderscaler.rs)
  - `max_render_pixel_ratio` f64: Render scale cap. (0 means no limit, negative values become 0)
- `pub fn is_view_rect_pending(&self) -> bool` (method, since 0.4.0): Returns whether the view area should be recalculated at the head of the next frame. (true if the maximum render pixel ratio was changed and not yet applied)
  - returns bool: true if a recalculation is still pending. (false once calculate_view_rect has fitted it)

  Example: Checking whether anything is left to fit after changing the maximum render pixel ratio

  ```rust
  use vanilla::{Vector2, ViewManager, ViewScaleMode};
  
  let mut view_manager = ViewManager::new(Vector2::create(1280.0, 720.0), ViewScaleMode::StretchShort);
  view_manager.set_max_render_pixel_ratio(1.0);
  assert!(view_manager.is_view_rect_pending());
  view_manager.calculate_view_rect(1280, 720, 1.0);
  assert!(!view_manager.is_view_rect_pending());
  ```

- `pub fn get_max_render_pixel_ratio(&self) -> f64` (method, since 0.4.0): Returns the render scale upper limit.
  - returns f64: Render scale cap. (0 means no limit, default 0)
- `pub fn limit_render_pixel_ratio(&self, device_pixel_ratio: f64) -> f64` (method, since 0.4.0): Applies the render scale cap to the device scale factor. (unchanged if the cap is 0 or the scale is at or below the cap, called by the web when setting the canvas size and by desktop when setting the draw size)
  - `device_pixel_ratio` f64: Device scale.
  - returns f64: Capped scale.

  Example: With a cap of 2, a scale of 3 becomes 2

  ```rust
  use vanilla::{Vector2, ViewManager, ViewScaleMode};
  
  let mut view_manager = ViewManager::new(Vector2::create(1280.0, 720.0), ViewScaleMode::StretchShort);
  view_manager.set_max_render_pixel_ratio(2.0);
  assert_eq!(view_manager.limit_render_pixel_ratio(3.0), 2.0);
  assert_eq!(view_manager.limit_render_pixel_ratio(1.5), 1.5);
  ```

- `pub fn apply_aspect_view_scale_mode(&mut self)` (method, since 0.4.0): Automatically picks the view scale mode that fits the aspect ratio. (recomputes the view area right away if it changes)
  - If the screen is taller than the reference resolution, it fixes the width and expands the height (StretchWidthExpandHeight),
    and if it is wider, it fixes the height and expands the width (StretchHeightExpandWidth). (logic several games used to copy and paste)

  Example: A tall window fixes the width and expands the height

  ```rust
  use vanilla::{Vector2, ViewManager, ViewScaleMode};
  
  let mut view_manager = ViewManager::new(Vector2::create(1280.0, 720.0), ViewScaleMode::StretchShort);
  view_manager.calculate_view_rect(1500, 2000, 2.0);
  view_manager.apply_aspect_view_scale_mode();
  assert_eq!(view_manager.get_view_scale_mode(), ViewScaleMode::StretchWidthExpandHeight);
  assert_eq!(view_manager.get_view_size(), Vector2::create(1280.0, 1707.0));
  ```

- `pub fn set_safe_area_override(&mut self, insets: Option<SafeAreaInsets>)` (method, since 0.4.0): Sets a forced safe area value. (CSS pixels, for mimicking a notch on desktop, None clears it)
  - `insets` Option<SafeAreaInsets>: Insets to force. (CSS pixels) None clears it and uses the URL value or the CSS value.
- `pub fn get_safe_area_insets(&self) -> SafeAreaInsets` (method, since 0.4.0): Safe area insets. (view coordinates)
  - Priority: set_safe_area_override > URL ?safeArea=top,right,bottom,left > measured CSS env(safe-area-inset-*).
  - Converts CSS pixels to view coordinates by dividing by the reference resolution scale.
  - returns SafeAreaInsets: Insets in view coordinates. (0 for ignored sides, CSS pixels as they are if the scale is 0 or less)
- `pub fn set_ignored_safe_area_sides(&mut self, sides: &[SafeAreaSide])` (method, since 0.4.0): Sets the safe area sides to ignore. (get_safe_area_insets returns 0 for those sides, an empty list uses all of them)
  - The game decides which sides to ignore and passes them in, as with a web view where the platform's app already draws around those sides.
  - `sides` &[SafeAreaSide]: List of sides to ignore. (copied and kept)

  Example: Ignore the top and left

  ```rust
  use vanilla::{SafeAreaInsets, SafeAreaSide, Vector2, ViewManager, ViewScaleMode};
  
  let mut view_manager = ViewManager::new(Vector2::create(1280.0, 720.0), ViewScaleMode::None);
  view_manager.calculate_view_rect(1280, 720, 1.0);
  view_manager.set_safe_area_override(Some(SafeAreaInsets::create(40.0, 10.0, 30.0, 20.0)));
  view_manager.set_ignored_safe_area_sides(&[SafeAreaSide::Top, SafeAreaSide::Left]);
  assert_eq!(view_manager.get_safe_area_insets(), SafeAreaInsets::create(0.0, 10.0, 30.0, 0.0));
  ```

- `pub fn get_ignored_safe_area_sides(&self) -> &[SafeAreaSide]` (method, since 0.4.0): Returns the safe area sides to ignore.
  - returns &[SafeAreaSide]: List of sides to ignore. (empty list by default)
- `pub fn canvas_position_to_view_position(&self, canvas_position: Vector2) -> Vector2` (method, since 0.3.2): Logical inner window coordinates → view coordinates.
  - `canvas_position` Vector2: Logical inner window coordinates. (top left is 0)
  - returns Vector2: View coordinates. (rounded, (0, 0) if the scale is 0)
- `pub fn convert_client_to_view(&self, client_x: f64, client_y: f64) -> Vector2` (method, since 0.4.0): Converts screen (client) coordinates to view coordinates. (subtracts the canvas's current position and converts with canvas_position_to_view_position)
  - `client_x` f64: Screen x. (logical pixels, relative to the page on the web, relative to the inner window on desktop)
  - `client_y` f64: Screen y. (logical pixels)
  - returns Vector2: View coordinates. (rounded)

## SafeAreaSide (enum) (Clone, Copy, Debug, PartialEq, Eq)

A side of the safe area. (the original "top", "right", "bottom", "left")

- `Top`: Top. (the original "top")
- `Right`: Right. (the original "right")
- `Bottom`: Bottom. (the original "bottom")
- `Left`: Left. (the original "left")

## ViewScaleMode (enum) (Clone, Copy, Debug, PartialEq, Eq)

View scale mode.

- `None`: Disabled (the view area also changes when the window size changes)
- `ReferenceResolution`: Defines the view area by the reference resolution (both axes may be cropped or have leftover space)
- `StretchWidth`: Reference resolution + stretches to fit along the horizontal axis while keeping the aspect ratio. (The opposite axis may be cropped or have leftover space)
- `StretchHeight`: Reference resolution + stretches to fit along the vertical axis while keeping the aspect ratio. (The opposite axis may be cropped or have leftover space)
- `StretchShort`: Reference resolution + stretches to fit along the shorter of the two axes while keeping the aspect ratio. (The opposite axis may have leftover space)
- `StretchWidthExpandHeight`: Stretches the width across the whole screen. The height is computed automatically from the screen ratio. No margins.
- `StretchHeightExpandWidth`: Stretches the height across the whole screen. The width is computed automatically from the screen ratio. No margins.
- `StretchShortExpandLong`: Scales by the short axis. The long axis is also stretched across the whole screen. No margins.

- `pub fn get_name(&self) -> &'static str` (method, since 0.4.0): Name text same as the original. (the value of the original ViewScaleMode, camel case like "stretchShort")
  - returns &'static str: Name text. ("none", "referenceResolution", "stretchWidth", "stretchHeight", "stretchShort", "stretchWidthExpandHeight", "stretchHeightExpandWidth", "stretchShortExpandLong")

  Example: Writing the mode name in the statistics text

  ```rust
  use vanilla::ViewScaleMode;
  
  assert_eq!(ViewScaleMode::StretchShort.get_name(), "stretchShort");
  assert_eq!(format!("viewScaleMode: {}", ViewScaleMode::ReferenceResolution.get_name()), "viewScaleMode: referenceResolution");
  ```

