vanilladocs
vanillapunch.com
API / base/platform

base/platform

플랫폼 정보. (원본 base/platform.js)

  • 원본은 navigator.user_agent 를 보고 플랫폼과 브라우저를 고른다.
  • 러스트 판은 웹(wasm32)에서는 원본과 같은 규칙으로 user_agent 를 보고, 데스크탑에서는 빌드 대상 OS 를 쓴다. 데스크탑의 브라우저는 Chrome 이다. 데스크탑 판은 크롬 위에서 도는 원본과 같은 결과를 내도록 맞췄고(글꼴과 글자 너비, 주된 손 판정, 페이지 이벤트, 세이프 에어리어, 화면 키보드), 원본은 이 이름을 개발자 도구와 통계 글에 보이기만 하므로, 게임 코드의 브라우저 분기도 크롬 갈래로 가야 같은 결과다. 리눅스는 스팀덱이면 SteamDeck 이다. 스팀이 스팀덱에서 띄울 때 넣는 환경 변수 SteamDeck=1 (밸브 Proton 실행 스크립트가 이것으로 스팀덱을 가린다), 또는 밸브 SteamOS 의 jupiter-hw-support 처럼 /sys/class/dmi/id/board_vendor 가 Valve 이고 board_name 이 Jupiter(LCD) 나 Galileo(OLED) 이면 스팀덱으로 본다.
  • 원본의 getOrAddCanvas 는 platform/web.rs 가 엔진 설정의 캔버스 id 로 한다.
  • get_resource_usage: 웹은 원본처럼 performance 의 resource 항목을 더한다. 데스크탑은 네트워크로 받은 것이 없어, 엔진이 애셋으로 읽은 파일(애셋 바이트 읽기, Engine::load_image, 오디오 파일)을 읽은 차례로 든다. 종류는 "file", 전송량과 푼 크기는 둘 다 파일 바이트 수다. (기본 글꼴과 대체 글꼴처럼 시스템에서 읽는 글꼴은 원본의 시스템 글꼴처럼 들지 않는다) 옛 이름의 오타 get_resouce_usage 는 같은 함수를 부르는 별칭으로 남긴다. (원본도 같다)
  • get_safe_area_rect: 원본은 캔버스(없으면 창)의 크기를 읽는다. 러스트 판은 문서 객체가 없어 그 크기를 받는다. 데스크탑의 인셋은 크롬 데스크탑처럼 0 이다.
  • is_coarse_pointer: 원본처럼 CSS pointer: coarse. 데스크탑은 크로미엄의 판정을 옮겼다. (윈도우는 태블릿 모드나 마우스 없는 터치 기기, 리눅스는 마우스와 터치패드 없이 터치스크린만 있을 때 참, 맥은 늘 거짓. platform/desktop.rs)
  • is_desktop_web: 원본은 부를 때마다 플랫폼 정보를 새로 읽는다. 러스트 판은 만들 때 읽은 것을 쓴다. (user_agent 는 바뀌지 않는다) 데스크탑 빌드는 모바일이 아니고 손가락 입력 수(navigator.maxTouchPoints)가 없어 늘 true 다.

Platform information. (the original base/platform.js)

  • The original picks the platform and browser by looking at navigator.user_agent.
  • The Rust version looks at user_agent with the same rules as the original on the web (wasm32), and uses the build target OS on desktop. The desktop browser is Chrome. The desktop version is tuned to give the same results as the original running on Chrome (fonts and glyph widths, primary pointer detection, page events, safe area, on-screen keyboard), and the original only shows this name in developer tools and statistics text, so browser branches in game code must also take the Chrome branch to get the same results. On Linux it is SteamDeck if running on a Steam Deck. It counts as a Steam Deck if the environment variable SteamDeck=1 that Steam sets when launching on a Steam Deck is present (Valve's Proton launch script tells the Steam Deck apart by this), or if, like Valve SteamOS's jupiter-hw-support, /sys/class/dmi/id/board_vendor is Valve and board_name is Jupiter (LCD) or Galileo (OLED).
  • The original's getOrAddCanvas is done by platform/web.rs with the canvas id from the engine settings.
  • get_resource_usage: on the web, adds up performance's resource entries as in the original. On desktop nothing is received over the network, so it lists the files the engine read as assets (asset byte reads, Engine::load_image, audio files) in the order read. The type is "file", and both the transfer size and the decoded size are the file's byte count. (fonts read from the system, such as the default and fallback fonts, are not listed, just like the original's system fonts) The old misspelled name get_resouce_usage remains as an alias calling the same function. (same in the original)
  • get_safe_area_rect: the original reads the size of the canvas (or the window if none). The Rust version has no document object, so it takes that size. Insets on desktop are 0 like desktop Chrome.
  • is_coarse_pointer: CSS pointer: coarse as in the original. On desktop, Chromium's detection was ported. (true on Windows in tablet mode or on a touch device without a mouse, on Linux when there is only a touchscreen without a mouse or touchpad, always false on Mac. platform/desktop.rs)
  • is_desktop_web: the original reads the platform information anew on every call. The Rust version uses what it read at creation. (user_agent does not change) Desktop builds are not mobile and have no touch point count (navigator.maxTouchPoints), so it is always true.

Platformstruct traits Clone, Debug, Default

짝Counterpart: vanilla.js Platform소스source

플랫폼 정보.

Platform information.

예제Exampleuser_agent 로 플랫폼과 브라우저 고르기Pick the platform and browser from user_agent
use vanilla::{BrowserType, Platform, PlatformType};

let mut platform = Platform::new();
platform.apply_user_agent("Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1");
assert_eq!(platform.get_platform_name(), PlatformType::IOs);
assert_eq!(platform.get_platform_name().get_name(), "iOS");
assert_eq!(platform.get_browser_name(), BrowserType::Safari);
assert!(platform.is_mobile());
assert!(!platform.is_desktop_web());
예제Example엔진의 플랫폼 정보로 단축키 안내를 보일지 가리기Decide whether to show shortcut hints from the engine's platform information
use vanilla::Engine;

fn is_shortcut_hint_visible(engine: &Engine) -> bool {
	let platform = engine.get_platform();
	platform.is_desktop_web() && !platform.is_coarse_pointer()
}
생성자constructorpub fn new() -> Platform#0.3.2 부터since 0.3.2소스source

생성. (탐지까지 한다. 원본은 생성 뒤 get_platform_info 를 부른다)

Constructor. (also performs detection. The original calls get_platform_info after construction)

반환ReturnsPlatform 탐지를 마친 플랫폼 정보. (웹은 navigator 의 user_agent, 데스크탑은 빌드 대상 OS 로 고른 것)Platform information with detection done. (picked from navigator's user_agent on the web, from the build target OS on desktop)

짝Counterpart: vanilla.js Platform.constructor

메서드methodpub fn get_platform_info(&mut self) -> (PlatformType, BrowserType)#0.3.2 부터since 0.3.2소스source

플랫폼 정보 탐지 및 적용. (플랫폼, 브라우저)

Detects and applies platform information. (platform, browser)

반환Returns(PlatformType, BrowserType) 다시 탐지해 넣은 (플랫폼, 브라우저). (모바일 여부도 다시 넣는다)The (platform, browser) detected again and stored. (the mobile flag is also stored again)

짝Counterpart: vanilla.js Platform.getPlatformInfo

메서드methodpub fn apply_user_agent(&mut self, user_agent: &str)#0.3.2 부터since 0.3.2소스source

user_agent 로 플랫폼과 브라우저 고르기. (원본 getPlatformInfo 의 정규식과 같은 순서, 대소문자 무시)

  • 모바일 여부도 같이 넣는다. (mobi, android, iphone, ipad 가 들면 모바일)

Picks the platform and browser from user_agent. (same order as the regular expressions of the original getPlatformInfo, case-insensitive)

  • Also stores the mobile flag. (mobile if it contains mobi, android, iphone or ipad)
user_agent&str
브라우저의 user_agent 글.The browser's user_agent string.

짝Counterpart: vanilla.js Platform.applyUserAgent

메서드methodpub fn get_platform_name(&self) -> PlatformType#0.3.2 부터since 0.3.2소스source

플랫폼.

Platform.

반환ReturnsPlatformType 탐지한 플랫폼.The detected platform.

짝Counterpart: vanilla.js Platform.platformName

메서드methodpub fn get_browser_name(&self) -> BrowserType#0.3.2 부터since 0.3.2소스source

브라우저.

Browser.

반환ReturnsBrowserType 탐지한 브라우저. (데스크탑 빌드는 Chrome)The detected browser. (Chrome for desktop builds)

짝Counterpart: vanilla.js Platform.browserName

메서드methodpub fn is_mobile(&self) -> bool#0.3.2 부터since 0.3.2소스source

모바일인지.

Whether it is mobile.

반환Returnsbool 모바일이면 true. (웹은 user_agent 로, 데스크탑 빌드는 안드로이드, iOS, 아이패드OS 대상일 때)true if mobile. (by user_agent on the web; for desktop builds, when targeting Android, iOS or iPadOS)

짝Counterpart: vanilla.js Platform.isMobile

메서드methodpub fn is_desktop_web(&self) -> bool#0.4.0 부터since 0.4.0소스source

데스크탑 웹인지. (마우스 휠, 키보드 안내처럼 데스크탑에서만 보일 것을 가릴 때 쓴다)

  • 모바일이면 아니다. 아이패드의 사파리는 데스크탑처럼 맥이라고 알리므로, 맥인데 손가락 입력이 여럿 되면 아이패드로 본다.

Whether it is desktop web. (used to pick out things shown only on desktop, such as mouse wheel and keyboard hints)

  • Not if mobile. Safari on iPad reports itself as Mac like a desktop, so a Mac with multiple touch points counts as an iPad.

반환Returnsbool 데스크탑 웹이면 true. (모바일이거나, 맥인데 navigator.maxTouchPoints 가 2 이상이면 false, 데스크탑 빌드는 늘 true)true if desktop web. (false if mobile, or a Mac with navigator.maxTouchPoints of 2 or more; always true for desktop builds)

짝Counterpart: vanilla.js Platform.isDesktopWeb

메서드methodpub fn is_coarse_pointer(&self) -> bool#0.4.0 부터since 0.4.0소스source

주된 손이 손가락인지. (CSS 의 pointer: coarse, 단축키 안내처럼 마우스로 하는 화면에만 보일 것을 가릴 때 쓴다)

Whether the primary pointer is a finger. (CSS pointer: coarse, used to pick out things shown only on mouse screens, such as shortcut hints)

반환Returnsbool 주된 손이 손가락이면 true. (부를 때마다 새로 읽는다, 맥 데스크탑은 늘 false)true if the primary pointer is a finger. (read anew on every call, always false on Mac desktop)

짝Counterpart: vanilla.js Platform.isCoarsePointer

메서드methodpub fn get_resource_usage(&self) -> ResourceUsage#0.4.0 부터since 0.4.0소스source

리소스 사용량. (웹이 받은 파일마다 전송량과 푼 크기)

Resource usage. (transfer size and decoded size of each file the web received)

반환ReturnsResourceUsage 지금까지 받은 파일 목록과 그 합. (부를 때마다 새로 모은다, 데스크탑은 엔진이 애셋으로 읽은 파일)List of files received so far and their totals. (gathered anew on every call; on desktop, the files the engine read as assets)

짝Counterpart: vanilla.js Platform.getResourceUsage

메서드methodpub fn get_resouce_usage(&self) -> ResourceUsage#0.4.0 부터since 0.4.0소스source

리소스 사용량. (옛 이름의 오타를 그대로 둔 별칭, get_resource_usage 와 같다)

Resource usage. (an alias keeping the old misspelled name, same as get_resource_usage)

반환ReturnsResourceUsage get_resource_usage 와 같은 값.Same value as get_resource_usage.

짝Counterpart: vanilla.js Platform.getResouceUsage

메서드methodpub fn get_safe_area_rect(&self, area_size: Vector2) -> Rect#0.4.0 부터since 0.4.0소스source

세이프 에어리어. (area_size 크기에서 env(safe-area-inset-*) 를 뺀 사각형, 인셋은 원본 parseInt 처럼 정수로 자른다)

  • 인셋이 CSS 픽셀이므로 area_size 도 CSS 픽셀 크기로 준다. (원본처럼 캔버스의 CSS 크기 clientWidth, clientHeight 이고 그리기 버퍼 크기가 아니다) 너비와 높이는 0 이상이다.

Safe area. (the rectangle of area_size minus env(safe-area-inset-*), insets truncated to integers like the original parseInt)

  • The insets are CSS pixels, so give area_size in CSS pixels too. (like the original, the canvas CSS size clientWidth, clientHeight, not the drawing buffer size) Width and height are 0 or more.
area_sizeVector2
인셋을 뺄 바탕 크기. (픽셀, 원본의 캔버스 크기 자리)Base size to subtract the insets from. (pixels, in place of the original's canvas size)

반환ReturnsRect (왼쪽 인셋, 위 인셋) 에서 시작하고, 너비는 좌우 인셋을, 높이는 위아래 인셋을 뺀 사각형.A rectangle starting at (left inset, top inset), with the left and right insets taken from the width and the top and bottom insets taken from the height.

짝Counterpart: vanilla.js Platform.getSafeAreaRect

예제Example데스크탑은 인셋이 0 이라 받은 크기 그대로다On desktop the insets are 0, so it is the given size as is
use vanilla::{Platform, Rect, Vector2};

let platform = Platform::new();
let safe_area_rect = platform.get_safe_area_rect(Vector2::create(800.0, 600.0));
assert_eq!(safe_area_rect, Rect::create(0.0, 0.0, 800.0, 600.0));

LoadedFilestruct traits Clone, Debug, PartialEq

소스source

받은 파일 하나. (원본 loadedFiles 의 { path, name, type, transferSize, decodedSize })

One received file. (the original loadedFiles' { path, name, type, transferSize, decodedSize })

예제Example가장 큰 파일 찾기Find the largest file
use vanilla::base::platform::LoadedFile;
use vanilla::Platform;

let platform = Platform::new();
let resource_usage = platform.get_resource_usage();
let largest_file: Option<&LoadedFile> = resource_usage.loaded_files.iter().max_by(|first, second| first.decoded_size.total_cmp(&second.decoded_size));
if let Some(loaded_file) = largest_file {
	println!("{} {}", loaded_file.path, loaded_file.decoded_size);
}
필드fieldpub path: String#0.4.0 부터since 0.4.0소스source

경로. (웹은 performance 항목의 name 인 주소, 데스크탑은 엔진이 읽은 애셋 경로)

Path. (on the web, the URL that is the performance entry's name; on desktop, the asset path the engine read)

반환ReturnsString

필드fieldpub name: String#0.4.0 부터since 0.4.0소스source

경로의 마지막 조각인 파일 이름. (웹은 / 로, 데스크탑은 / 와 \ 로 가른다)

File name, the last segment of the path. (split by / on the web, by / and \ on desktop)

반환ReturnsString

필드fieldpub resource_type: String#0.4.0 부터since 0.4.0소스source

종류. (웹은 initiatorType, 데스크탑은 "file")

Type. (initiatorType on the web, "file" on desktop)

반환ReturnsString

필드fieldpub transfer_size: f64#0.4.0 부터since 0.4.0소스source

전송량. (바이트, 웹은 transferSize, 데스크탑은 파일 바이트 수)

Transfer size. (bytes, transferSize on the web, the file's byte count on desktop)

반환Returnsf64

필드fieldpub decoded_size: f64#0.4.0 부터since 0.4.0소스source

푼 크기. (바이트, 웹은 decodedBodySize, 데스크탑은 파일 바이트 수)

Decoded size. (bytes, decodedBodySize on the web, the file's byte count on desktop)

반환Returnsf64

ResourceUsagestruct traits Clone, Debug, Default, PartialEq

소스source

리소스 사용량. (원본 { totalTransferSize, totalDecodedSize, loadedFiles })

Resource usage. (the original { totalTransferSize, totalDecodedSize, loadedFiles })

예제Example합은 파일마다의 값을 더한 것이다The totals are the sums of each file's values
use vanilla::Platform;

let platform = Platform::new();
let resource_usage = platform.get_resource_usage();
let total_transfer_size: f64 = resource_usage.loaded_files.iter().map(|loaded_file| loaded_file.transfer_size).sum();
assert_eq!(total_transfer_size, resource_usage.total_transfer_size);
println!("{} {}", resource_usage.loaded_files.len(), resource_usage.total_decoded_size);
필드fieldpub total_transfer_size: f64#0.4.0 부터since 0.4.0소스source

전송량 합. (바이트)

Total transfer size. (bytes)

반환Returnsf64

필드fieldpub total_decoded_size: f64#0.4.0 부터since 0.4.0소스source

푼 크기 합. (바이트)

Total decoded size. (bytes)

반환Returnsf64

필드fieldpub loaded_files: Vec<LoadedFile>#0.4.0 부터since 0.4.0소스source

받은 파일 목록. (데스크탑은 읽은 차례)

List of received files. (in read order on desktop)

반환ReturnsVec<LoadedFile>

상수Constants

상수constantpub const SYSTEM_FONT_STRING: &str#0.3.2 부터since 0.3.2소스source

공통 시스템 폰트 목록. (원본 SYSTEM_FONT_STRING, 웹 CSS 글꼴 목록)

Common system font list. (the original SYSTEM_FONT_STRING, a web CSS font list)

반환Returns&str

PlatformTypeenum traits Clone, Copy, Debug, PartialEq, Eq

짝Counterpart: vanilla.js PlatformType소스source

플랫폼 타입.

Platform type.

이름Name설명Description
Windows윈도우.Windows.
MacOs맥OS. (웹은 user_agent 의 macintosh 나 mac os x)macOS. (macintosh or mac os x in user_agent on the web)
Android안드로이드.Android.
SteamDeck스팀덱. (웹은 user_agent 의 valve steam gameoverlay, 데스크탑은 리눅스 가운데 스팀덱으로 가린 것)Steam Deck. (valve steam gameoverlay in user_agent on the web; on desktop, Linux identified as a Steam Deck)
IPadOs아이패드OS. (웹은 user_agent 의 ipad)iPadOS. (ipad in user_agent on the web)
IOsiOS. (웹은 user_agent 의 iphone 이나 ipod)iOS. (iphone or ipod in user_agent on the web)
Linux리눅스. (스팀덱이 아닌 것)Linux. (not a Steam Deck)
Unknown위 어느 것도 아닌 것.None of the above.
메서드methodpub fn get_name(&self) -> &'static str#0.3.2 부터since 0.3.2소스source

원본과 같은 이름 글. ("Windows", "macOS" ...)

Name string, same as the original. ("Windows", "macOS" ...)

반환Returns&'static str 이름 글. ("Windows", "macOS", "Android", "SteamDeck", "iPadOS", "iOS", "Linux", "Unknown")Name string. ("Windows", "macOS", "Android", "SteamDeck", "iPadOS", "iOS", "Linux", "Unknown")

BrowserTypeenum traits Clone, Copy, Debug, PartialEq, Eq

짝Counterpart: vanilla.js BrowserType소스source

브라우저 타입.

Browser type.

이름Name설명Description
Chrome크롬. (데스크탑 빌드는 늘 이것)Chrome. (always this for desktop builds)
Edge엣지. (웹은 user_agent 의 edg, 크롬보다 먼저 본다)Edge. (edg in user_agent on the web, checked before Chrome)
Firefox파이어폭스.Firefox.
InternetExplorer인터넷 익스플로러. (웹은 user_agent 의 msie 나 trident)Internet Explorer. (msie or trident in user_agent on the web)
Safari사파리. (웹은 user_agent 에 edg 와 chrome 이 없고 safari 가 든 것)Safari. (on the web, user_agent containing safari without edg and chrome)
Unknown위 어느 것도 아닌 것.None of the above.
메서드methodpub fn get_name(&self) -> &'static str#0.3.2 부터since 0.3.2소스source

원본과 같은 이름 글. ("Chrome", "Edge" ...)

Name string, same as the original. ("Chrome", "Edge" ...)

반환Returns&'static str 이름 글. ("Chrome", "Edge", "Firefox", "Internet Explorer", "Safari", "Unknown")Name string. ("Chrome", "Edge", "Firefox", "Internet Explorer", "Safari", "Unknown")