# core/engine (vanilla.js 0.4.0)

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

엔진.

## EngineConfiguration extends Object

엔진 설정.

예제: 설정을 채워 엔진 만들기

```js
import { Engine, EngineConfiguration, Scene, Vector2, ViewScaleMode, ColorSpace } from "./build/vanilla.js";

const engineConfiguration = new EngineConfiguration();
engineConfiguration.canvasId = "gameCanvas";
engineConfiguration.title = "My Game";
engineConfiguration.referenceResolutionSize = Vector2.create(1920, 1080);
engineConfiguration.viewScaleMode = ViewScaleMode.stretchShortExpandLong;
engineConfiguration.autoResizeOnWindowResize = true;
engineConfiguration.maximumFramePerSecond = 60;
engineConfiguration.antialias = true;
engineConfiguration.useStatistics = true;
engineConfiguration.useDevTools = false;
engineConfiguration.colorSpace = ColorSpace.gamma;
const engine = new Engine(engineConfiguration);
engine.run(new Scene());
```

- `referenceResolutionSize` (field, since 0.0.8): 기준 해상도.
  - returns Vector2
- `viewScaleMode` (field, since 0.4.0): 뷰 스케일 모드. (기본 ViewScaleMode.stretchShort, 엔진이 만들 때 뷰 매니저에 넣는다. UIScene 과 GameScene 은 initialize 에서 저마다의 모드로 바꾼다)
  - returns string
- `canvasId` (field, since 0.0.8): 캔버스 식별자. 문서에 그 id 의 요소가 없으면 캔버스를 새로 만들어 그 id 를 주고 body 끝에 붙인다.
  - returns string
- `useStatistics` (field, since 0.0.9): 정보창 출력 여부.
  - returns boolean
- `autoResizeOnWindowResize` (field, since 0.0.9): 윈도우가 리사이즈 될 때 캔버스 사이즈 자동 반영.
  - returns boolean
- `title` (field, since 0.2.0): 이름.
  - returns string
- `preserveDrawingBuffer` (field, since 0.3.1): 프레임이 끝난 뒤에도 그린 것을 캔버스에 남길지. 캔버스 위에 후처리를 얹는 프로젝트가 켠다.
  (다른 캔버스가 texImage2D 나 drawImage 로 읽으려면 필요하다) 한 번 더 복사하는 만큼 비용이 있다.
  - returns boolean
- `antialias` (field, since 0.4.0): 캔버스(기본 프레임 버퍼)의 멀티샘플 안티에일리어싱(MSAA)을 켤지. 생성 때 정한다. 켜면(기본) 지금까지와 같다.
  끄면 도형과 3D 의 가장자리가 계단져 보이는 대신 고해상도 모바일에서 프레임마다 드는 리졸브 비용이 빠진다.
  (웹은 WebGL 컨텍스트 속성 antialias 로 켬과 끔만 고르고 표본 수는 브라우저가 정한다. 데스크탑은 켜면 표본 4)
  후처리(ToonPostProcess)가 자기 MSAA 판에 그리므로 그걸 쓰는 게임은 캔버스 antialias 를 false 로 짓는다.
  true 면 캔버스 자체가 MSAA 라 화면에 옮기는 패스와 UI 가 표본마다 섞여 값이 더 든다.
  (맥미니 2560x1440 툰 후처리 장면 GPU 처리량 6.89 → 6.49 ms, 끈 판 6.81 → 5.22 ms)
  예: engineConfiguration.antialias = false; (ToonPostProcess 를 쓰는 게임)
  - returns boolean
- `maximumFramePerSecond` (field, since 0.3.2): 최대 FPS. 0 이면 제한하지 않는다. (화면 주사율을 따른다) 정하면 그보다 빨리 온 프레임은 건너뛰어
  주사율이 높거나 프레임이 들쭉날쭉한 기기에서도 고른 간격으로 돈다.
  - returns number
- `defaultFontUrl` (field, since 0.3.2): 기본 글꼴 주소. (처음은 빈 글, 러스트 판 default_font_url 과 같다) 주면 run() 이 뒤에서 받아 글꼴 이름 "default" 로 올린다.
  - 글꼴 이름 "default"(엔진 기본 글꼴 사슬)의 첫 글꼴이 되고, 그 뒤는 시스템 글꼴 사슬 SYSTEM_FONT_STRING 이다. 비우면 받지 않고 시스템 글꼴로 그린다.
  - 엔진은 글꼴을 따로 받지 않는다. 게임 글꼴은 이 주소나 FontAsset 으로 넣는다.
  - returns string
- `ignoreVirtualKeyboardResize` (field, since 0.3.2): 글자 입력칸이 포커스된 동안 가로는 그대로이고 세로만 줄어드는 리사이즈를 무시할지. (모바일의 화면 키보드)
  끄면(기본) iOS 사파리에서 키보드가 뜰 때 visualViewport 의 세로가 줄어 캔버스와 화면 전체가 작아진다. 키보드가 내려가면 다시 맞춘다.
  - returns boolean
- `rebakeTextOnFontLoad` (field, since 0.3.2): 웹 폰트가 늦게 받아지면 그 폰트로 구운 글자 텍스처 가운데 그 폰트의 글자 범위에 든 것만 버려 다시 굽게 할지.
  끄면(기본) 받기 전에 다른 폰트로 구운 글자는 캐시에서 밀려날 때까지 그대로 남는다.
  (unicode-range 로 나눈 폰트 조각을 그때그때 받는 프로젝트가 켠다. 받은 조각마다 그 글자만 다시 구우므로 프레임이 크게 길어지지 않는다)
  - returns boolean
- `useDevTools` (field, since 0.3.2): 개발자 도구(F2 로 여닫는 패널과 기즈모)를 쓸지. 끄면 GameScene 이 만들지 않고 F2 도 받지 않는다.
  (켜면(기본) 지금까지와 같다. 출시 빌드처럼 사용자에게 보이면 안 되는 곳에서 끈다)
  - returns boolean
- `maxCanvasAspectRatio` (field, since 0.3.2): 캔버스의 긴 쪽이 짧은 쪽의 몇 배까지인지. 0 이면 제한하지 않는다. (기본, 지금까지와 같다)
  정하면 autoResizeOnWindowResize 로 맞출 때 창이 그보다 길쭉하면 캔버스를 그 비까지 줄여 창의 가운데에 둔다. (남는 곳은 페이지의 바탕)
  (게임 영역의 가로세로 비를 제한하는 포털처럼, 캔버스가 창을 다 채우면 안 되는 곳에서 정한다)
  - returns number
- `resumeAudioOnTouchEnd` (field, since 0.3.2): 손을 뗄 때(touchend, pointerup)에도 오디오 컨텍스트를 깨울지. 생성 때 정한다.
  끄면(기본) 지금까지처럼 click, touchstart, keydown 에서만 깨운다. touchstart 는 사용자 활성화를 주지 않아,
  iOS WebKit 에서 앱 전환이나 전면 광고로 멈춘(suspended, interrupted) 컨텍스트를 화면을 끌기만 하는 게임이 다시 깨우지 못했다.
  (캔버스를 끄는 조작이 기본 동작을 막아 click 이 생기지 않는 게임이 켠다)
  - returns boolean
- `colorSpace` (field, since 0.4.0): 3D 색 공간. (ColorSpace.gamma 가 기본, 지금까지와 같은 화면. ColorSpace.linear 면 sRGB 텍스처와 sRGB 표준 곡선으로 선형 공간에서 빛을 셈한다)
  생성 때 정한다. 툰 렌더러, 후처리, 화면 바깥선, GLB 읽기가 따로 받지 않으면 이 값을 따른다. 2D 는 어느 값이든 감마 공간에서 합성한다. (유니티 Player Settings 의 Color Space)
  - returns string
- `trackGpuMemory` (field, since 0.4.0): GPU 메모리 셈(개발용)을 처음부터 켤지. 생성 때 정한다. 끄면(기본) GL 짓기 호출을 가로채지 않아 프레임 CPU 에 드는 값이 없다.
  켜면 엔진이 처음 짓는 자원까지 센다. 나중에 켜려면 Engine.enableGpuMemoryTracking() 이고 그 뒤에 지은 것부터 센다.
  예: engineConfiguration.trackGpuMemory = true; (프로파일링 때)
  - returns boolean
- `constructor()` (constructor, since 0.0.8): 생성.

## Engine extends Object

엔진.

예제: 씬 하나로 엔진 돌리기

```js
import { Engine, EngineConfiguration, Scene, Vector2, Rect, Colors } from "./build/vanilla.js";

class MainScene extends Scene {
	draw(graphic) {
		super.draw(graphic);
		graphic.setFillColor(Colors.white);
		graphic.drawRect(Rect.create(100, 100, 200, 120));
	}
}

const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
engineConfiguration.autoResizeOnWindowResize = true;
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor(engineConfiguration)` (constructor, since 0.0.8): 생성.
  - `engineConfiguration` EngineConfiguration: 엔진 설정. (EngineConfiguration 이 아니면 예외를 던진다)
- `run(scene)` (method, since 0.0.8): 시작.
  - `scene` Scene: 처음 불러올 씬. (Scene 이 아니면 예외를 던진다)
- `resume()` (method, since 0.0.10): 오디오 컨텍스트 재개.
- `resumeOnUserGesture()` (method, since 0.2.1): 첫 user gesture (click/touch/keydown) 핸들러.
  AudioManager 에 user gesture 발생을 알리고 컨텍스트 재개를 시도한다.
- `resize()` (method, since 0.0.8): 해상도 변경됨.
- `isTextInputFocused()` (method, since 0.3.2): 글자 입력칸이 포커스되어 있는지. (input 의 글자 종류, textarea, contenteditable)
  - returns boolean: 글자 입력칸이 포커스되어 있으면 참.
- `setupAllDocumentEvents()` (method, since 0.0.8): 웹페이지에 기반하는 이벤트 설정.
- `updateTouchPoints(touchEvent)` (method, since 0.4.0): 손가락 목록 갱신. (터치 사건의 바뀐 손가락마다 닿음, 움직임, 뗌을 적고, 사건의 touches 에 없는 손가락은 취소로 지운다)
  - `touchEvent` TouchEvent: 브라우저의 터치 사건.
- `updateCanvasNativeInputPosition(x, y)` (method, since 0.0.8): 입력 좌표 갱신.
  - `x` number: 클라이언트 X 좌표. (CSS 픽셀, clientX)
  - `y` number: 클라이언트 Y 좌표. (CSS 픽셀, clientY)
- `drawStatistics(graphic)` (method, since 0.0.8): 개발 관련 정보 출력.
  - `graphic` Graphic: 그릴 그래픽.
- `updateEngine(timestamp)` (method, since 0.0.8): 엔진 갱신.
  - `timestamp` number: requestAnimationFrame 이 넘긴 시각. (밀리초)
- `measureGpuThroughput(frameCount = 120)` (method, since 0.4.0): GPU 처리량 재기. (지금 장면을 갱신 없이 그리기만 잇달아 하고 GPU 가 다 그리길 기다린 프레임당 시간)
  - 지금 장면을 씬 갱신(tick) 없이 엔진 프레임과 같은 그리기 길로 frameCount 번 잇달아 그리고, 1 화소 readPixels 로 GPU 가 다 그리길 기다린 벽시계 시간을 프레임 수로 나눈다.
    렌더러(스크립트와 GL 명령 쓰기), GPU 프로세스(명령 풀기), GPU 실행 가운데 가장 느린 단의 몫이다. GPU 가 가장 느리면 GPU 가 실제로 한 프레임을 그리는 시간이다.
    (크롬 트레이스의 GPU 프로세스 메인 스레드 시간은 명령을 푸는 CPU 시간이라 GPU 가 그리는 양이 바뀌어도 거의 움직이지 않는다)
  - 다음 rAF 부터 시작한다. 데움 10 프레임 뒤 30 프레임씩 덩이로 나눠 rAF 하나에 한 덩이를 그리고 덩이마다 GPU 를 기다린다. (한 번에 길게 막지 않는다, 덩이 사이는 재지 않는다)
  - 재는 동안 엔진 시간, 입력, 엔진 프레임 함수, 프레임 번호, 화면 크기 맞추기, 찍기는 서 있고 씬의 tick 을 부르지 않는다. 씬의 draw 가 게임 상태를 바꾸지 않으면 게임 상태는 그대로다.
    다 재면 엔진 루프가 그대로 이어 돈다. (이어 도는 첫 프레임 간격은 탭을 숨겼다 돌아올 때처럼 TimeManager 의 간격 상한 안이다, 기본 0.25 초)
  - 같은 상태를 되풀이해 그리므로 바뀐 것만 다시 그리는 캐시(그림자 onChange 같은)는 다시 굽지 않는다. 움직이는 장면에서 프레임마다 다시 굽는 비용은 들지 않는다.
  - 캔버스의 기본 프레임 버퍼에 잇달아 그려 화면에 내는 것(합성)은 덩이마다 마지막 프레임만 한다. 합성 비용은 들지 않는다.
  - 페이지가 가려져 rAF 가 서면 기다린다. 재는 중에 또 부르거나 엔진 루프가 돌기 전이면 거부한다.
  - `frameCount` number: 잴 프레임 수. (1 이상의 정수, 데움은 빼고 센다)
  - returns Promise<{ frameCount: number, chunkFrameCount: number, millisecondsPerFrame: number, chunkMillisecondsPerFrame: number[] }>: 잰 프레임 수, 덩이 프레임 수, 프레임당 시간(밀리초, 모든 덩이 시간의 합 / 프레임 수), 덩이마다 프레임당 시간(밀리초).

  예제: 지금 장면의 GPU 처리량 재기

  ```js
  import { Engine, EngineConfiguration, Scene, Rect, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.setFillColor("#203040");
  		graphic.drawRect(Rect.create(0, 0, 640, 360));
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  const timeBefore = engine.getTimeManager().getTime();
  const result = await Engine.getEngine().measureGpuThroughput(60);
  const timeAfter = engine.getTimeManager().getTime();
  console.log(result.frameCount, result.chunkMillisecondsPerFrame.length, result.millisecondsPerFrame > 0, timeBefore === timeAfter);
  ```

- `setVisibleCursor(visibled)` (method, since 0.0.8): 커서 보이기 설정.
  - `visibled` boolean: 참이면 body 의 커서를 기본 커서로, 거짓이면 숨긴다.
- `getCanvas()` (method, since 0.0.8): 캔버스 정보 반환.
  - returns HTMLCanvasElement: 엔진이 그리는 캔버스.
- `getPlatform()` (method, since 0.0.8): 플랫폼 정보 반환.
  - returns Platform: 플랫폼 정보.
- `getTimeManager()` (method, since 0.0.8): 시간 매니저 반환.
  - returns TimeManager: 시간 매니저.
- `getViewManager()` (method, since 0.0.8): 뷰 매니저 반환.
  - returns ViewManager: 뷰 매니저.
- `getInputManager()` (method, since 0.0.8): 입력 매니저 반환.
  - returns InputManager: 입력 매니저.
- `getAudioManager()` (method, since 0.0.10): 오디오 매니저 반환.
  - returns AudioManager: 오디오 매니저.
- `getGraphic()` (method, since 0.0.9): 렌더러 반환.
  - returns Graphic: 렌더러.
- `getColorSpace()` (method, since 0.4.0): 3D 색 공간 반환. (생성 때 EngineConfiguration.colorSpace 로 정한 값, 툰 렌더러와 후처리의 기본값)
  - returns string: ColorSpace.gamma 나 ColorSpace.linear.

  예제: 엔진의 색 공간을 보고 색 공간마다 다른 값 고르기

  ```js
  import { Engine, EngineConfiguration, ColorSpace } from "./vanilla.js";
  const engine = new Engine(new EngineConfiguration());
  const exposure = engine.getColorSpace() === ColorSpace.linear ? 1.2 : 1;
  if (engine.getColorSpace() !== ColorSpace.gamma || exposure !== 1) {
  	throw new Error("default color space is not gamma");
  }
  ```

- `getVersionString()` (method, since 0.0.8): 버전 반환.
  - returns string: 엔진 판 글. ("주.부.패치", 갈래가 있으면 "-갈래" 를 붙임)
- `setMaximumFramePerSecond(maximumFramePerSecond)` (method, since 0.4.0): 최대 FPS 설정. (실행 중에 바꿀 수 있다, 0 이면 제한하지 않는다)
  - EngineConfiguration.maximumFramePerSecond 에 적는다. 엔진은 프레임마다 그 값을 읽어, 바뀌면 그 프레임부터 다시 센다.
  - 0 보다 작거나 숫자가 아니면 0 으로 둔다.
  - `maximumFramePerSecond` number: 최대 FPS. (0 이면 제한하지 않는다)
- `getMaximumFramePerSecond()` (method, since 0.4.0): 최대 FPS 반환. (0 이면 제한하지 않음)
  - returns number: 최대 FPS. (0 이면 제한하지 않음)
- `getEngineConfiguration()` (method, since 0.0.9): 엔진 설정 반환.
  - returns EngineConfiguration: 생성 때 받은 엔진 설정.
- `exitApplication()` (method, since 0.3.0): 응용 프로그램 종료.
  - Capacitor 네이티브면 App 플러그인으로 끝내고, 웹이면 창 닫기를 시도한다.
    (둘 다 환경에 따라 거부될 수 있으며 실패해도 예외를 내지 않는다)
- `openUrl(url)` (method, since 0.4.0): 바깥 주소 열기. (새 탭, 러스트 판 Engine::open_url 과 같다)
  - 웹: window.open(주소, "_blank", "noopener") 로 새 탭에 연다. 기존 페이지는 새 탭이 건드릴 수 없다.
  - 사용자 입력(누름, 탭, 키) 처리 안에서 부를 때만 열린다. 브라우저의 팝업 차단 규칙이다. 입력과 상관없이(타이머, 프레임) 부르면 막혀 열리지 않는다.
  - 열 수 있는 것은 http, https, mailto, tel 뿐이다. 그 밖의 꼴(javascript:, file: 같은)은 열지 않고 false.
  - `url` string: 열 주소. (http, https, mailto, tel)
  - returns boolean: 열기를 브라우저에 넘겼으면 참. (브라우저가 막았거나 주소가 맞지 않으면 거짓)

  예제: 열 수 없는 꼴은 거짓

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		const isOpened = engine.openUrl("javascript:alert(1)");
  		console.log(isOpened);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `readLocalTime(minuteOffset = 0)` (method, since 0.4.0): 현지 시각 읽기. (지금에서 분 오프셋만큼 더한 때를 이 기계의 시간대로 본 달력 시각, 러스트 판 Engine::read_local_time 과 같다)
  - 웹은 Date 로 읽는다. 더한 때의 일광 절약 시간까지 반영한다. (new Date(Date.now() + 오프셋) 과 같다)
  - `minuteOffset` number: 지금에 더할 분. (음수는 과거, 0 이면 지금)
  - returns { year: number, month: number, day: number, hour: number, minute: number, second: number, weekday: number }: 현지 시각. (해, 달 1 에서 12, 날, 시, 분, 초, 요일 0 이 일요일)

  예제: 지금 시각과 두 시간 앞뒤

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		const now = engine.readLocalTime();
  		const later = engine.readLocalTime(120);
  		const earlier = engine.readLocalTime(-120);
  		console.log(now.hour < 24 && now.month >= 1 && now.month <= 12, later.hour !== earlier.hour);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getFrameNumber()` (method, since 0.2.0): 현재 프레임 번호 반환.
  - returns number: 지금 프레임 번호. (run 을 부르면 1 이 되고 프레임을 마칠 때마다 1 씩 는다)
- `isExitRequested()` (method, since 0.4.0): 종료를 요청했는지. (exitApplication 을 불렀으면 참, 브라우저가 창 닫기를 거부해도 참)
  - returns boolean: exitApplication 을 불렀으면 참.
- `setTitle(title)` (method, since 0.4.0): 창 제목 설정. (탭 제목, document.title)
  - `title` string: 창 제목.
- `alert(message)` (method, since 0.4.0): 알림 창. (window.alert 자리, 엔진이 그린 창, 러스트 판 Engine::alert 와 같다)
  - 확인을 누르면 끝나는 손잡이를 돌려준다. (답은 늘 확인)
  - `message` string: 알릴 글.
  - returns ModalDialogHandle: 질문 창 손잡이.
- `confirm(message)` (method, since 0.4.0): 확인 창. (window.confirm 자리, 엔진이 그린 창, 러스트 판 Engine::confirm 과 같다)
  - `message` string: 물을 글.
  - returns ModalDialogHandle: 질문 창 손잡이. (확인하면 isConfirmed 가 참)
- `prompt(message, defaultValue = "")` (method, since 0.4.0): 입력 창. (window.prompt 자리, 엔진이 그린 창, 러스트 판 Engine::prompt 와 같다)
  - `message` string: 물을 글.
  - `defaultValue` string: 입력 칸의 기본값.
  - returns ModalDialogHandle: 질문 창 손잡이. (확인하면 getPromptText 가 입력한 글)
- `alertAsync(message)` (method, since 0.4.0): 알림 창을 띄우고 닫히면 풀리는 Promise. (러스트 판 Engine::alert_async)
  - `message` string: 알릴 글.
  - returns Promise<void>: 닫히면 풀린다.
- `confirmAsync(message)` (method, since 0.4.0): 확인 창을 띄우고 답하면 풀리는 Promise. (러스트 판 Engine::confirm_async)
  - `message` string: 물을 글.
  - returns Promise<boolean>: 확인하면 참.
- `promptAsync(message, defaultValue = "")` (method, since 0.4.0): 입력 창을 띄우고 답하면 풀리는 Promise. (러스트 판 Engine::prompt_async)
  - `message` string: 물을 글.
  - `defaultValue` string: 입력 칸의 기본값.
  - returns Promise<string | null>: 입력한 글. (취소하면 null)
- `isModalDialogOpen()` (method, since 0.4.0): 질문 창이 떠 있는지. (떠 있는 동안 엔진은 씬을 갱신하지 않는다, 러스트 판 Engine::is_modal_dialog_open 과 같다)
  - returns boolean: 떠 있으면 참.
- `writeClipboardText(text)` (method, since 0.4.0): 시스템 클립보드에 글 쓰기. (navigator.clipboard.writeText, 기다리지 않는다. 막히거나 없으면 아무것도 하지 않는다)
  - `text` string: 클립보드에 쓸 글.
- `async readClipboardText()` (method, since 0.4.0): 시스템 클립보드 글 읽기. (navigator.clipboard.readText, 브라우저는 비동기라 Promise. 글이 없거나 막히면 null)
  - 브라우저가 권한을 묻거나 사용자 입력 안에서만 허락할 수 있다.
  - returns Promise<string | null>: 클립보드의 글. (없거나 막히면 null)

  예제: 클립보드에 쓰고 읽기

  ```js
  import { Engine, EngineConfiguration } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.writeClipboardText("score: 100");
  const readPromise = engine.readClipboardText();
  readPromise.then((text) => {
  	if (text === null) {
  		console.log("clipboard blocked");
  	}
  	else {
  		console.log(text);
  	}
  });
  ```

- `isCoarsePointer()` (method, since 0.4.0): 주된 손이 손가락인지. (CSS 의 pointer: coarse)
  - returns boolean: 주된 손이 손가락이면 참.
- `loadScene(scene)` (method, since 0.4.0): 씬 불러오기. (SceneManager.loadScene 과 같다)
  - `scene` Scene: 불러올 씬.
  - returns Promise<void>: load, initialize 까지 마치면 끝나는 Promise. (이미 불러온 씬이면 바로 끝난다)

  예제: 씬 하나 더 불러오고 내리기

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  class GameScene extends Scene {
  }
  
  class PauseScene extends Scene {
  	initialize(engine) {
  		console.log("pause scene ready");
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new GameScene());
  const pauseScene = new PauseScene();
  await engine.loadScene(pauseScene);
  const isPauseSceneLoaded = pauseScene.isLoaded();
  console.log(isPauseSceneLoaded);
  await engine.unloadScene(pauseScene);
  const loadedScenes = engine.getAllLoadedScenes();
  console.log(loadedScenes.length);
  ```

- `unloadScene(scene)` (method, since 0.4.0): 씬 하나 내리기. (SceneManager.unloadScene 과 같다)
  - `scene` Scene: 내릴 씬.
  - returns Promise<void>: finalize, unload 를 마치고 목록에서 빼면 끝나는 Promise. (불러오지 않은 씬이면 바로 끝난다)
- `unloadAllScenes()` (method, since 0.4.0): 모든 씬 내리기. (SceneManager.unloadAllScenes 와 같다)
  - returns Promise<void>: 불러온 씬을 차례로 모두 내리면 끝나는 Promise.
- `getAllLoadedScenes()` (method, since 0.4.0): 불러온 씬 목록 반환. (불러온 차례, 러스트 판 get_all_loaded_scenes 와 같다)
  - returns Scene[]: 불러온 씬 목록. (엔진이 들고 있는 배열이라 고치지 않는다)

  예제: run 한 씬이 목록에 든다

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  console.log(engine.getAllLoadedScenes().length);
  ```

- `isPageHidden()` (method, since 0.4.0): 페이지가 가려져 있는지. (다른 탭, 앱 전환)
  - returns boolean: 페이지가 가려져 있으면 참.
- `addPageEventListener(pageEventListener)` (method, since 0.4.0): 페이지 이벤트 리스너 더하기. ((pageEvent) => void, PageEvent 의 값을 받는다)
  - `pageEventListener` Function: (pageEvent) => void. 같은 함수는 한 번만 더한다.

  예제: 페이지가 가려지면 멈추기

  ```js
  import { Engine, EngineConfiguration, Scene, PageEvent } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new Scene());
  const timeManager = engine.getTimeManager();
  const pageEventListener = (pageEvent) => {
  	if (pageEvent === PageEvent.hidden) {
  		timeManager.setTimeScale(0);
  	}
  	else if (pageEvent === PageEvent.visible) {
  		timeManager.setTimeScale(1);
  	}
  };
  engine.addPageEventListener(pageEventListener);
  const isPageHidden = engine.isPageHidden();
  console.log(isPageHidden);
  ```

- `removePageEventListener(pageEventListener)` (method, since 0.4.0): 페이지 이벤트 리스너 빼기.
  - `pageEventListener` Function: 더했던 리스너. (없으면 아무것도 하지 않는다)
- `addGraphicContextEventListener(graphicContextEventListener)` (method, since 0.4.0): 그래픽 컨텍스트 이벤트 리스너 더하기. ((graphicContextEvent) => void, GraphicContextEvent 의 값을 받는다)
  - `graphicContextEventListener` Function: (graphicContextEvent) => void. 같은 함수는 한 번만 더한다.

  예제: 컨텍스트를 되살리면 게임의 GL 객체 다시 짓기

  ```js
  import { Engine, EngineConfiguration, Scene, GraphicContextEvent } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  let isRebuildNeeded = false;
  engine.addGraphicContextEventListener((graphicContextEvent) => {
  	if (graphicContextEvent === GraphicContextEvent.restored) {
  		isRebuildNeeded = true;
  	}
  });
  console.log(isRebuildNeeded);
  ```

- `removeGraphicContextEventListener(graphicContextEventListener)` (method, since 0.4.0): 그래픽 컨텍스트 이벤트 리스너 빼기.
  - `graphicContextEventListener` Function: 더했던 리스너. (없으면 아무것도 하지 않는다)

  예제: 더한 리스너 빼기

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  const graphicContextEventListener = (graphicContextEvent) => {
  	console.log(graphicContextEvent);
  };
  engine.addGraphicContextEventListener(graphicContextEventListener);
  engine.removeGraphicContextEventListener(graphicContextEventListener);
  ```

- `addGraphicErrorListener(graphicErrorListener)` (method, since 0.4.0): 그래픽 오류 리스너 더하기. (({ kind, name, error }) => void, kind 는 GraphicErrorKind 의 값)
  - `graphicErrorListener` Function: ({ kind, name, error }) => void. 같은 함수는 한 번만 더한다.

  예제: 셰이더 짓기 실패를 받아 기록하기

  ```js
  import { Engine, EngineConfiguration, Scene, GraphicErrorKind } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  const failedNameList = [];
  engine.addGraphicErrorListener((graphicError) => {
  	if (graphicError.kind === GraphicErrorKind.shaderBuildFailed) {
  		failedNameList.push(graphicError.name);
  	}
  });
  console.log(failedNameList.length);
  ```

- `removeGraphicErrorListener(graphicErrorListener)` (method, since 0.4.0): 그래픽 오류 리스너 빼기.
  - `graphicErrorListener` Function: 더했던 리스너. (없으면 아무것도 하지 않는다)

  예제: 더한 오류 리스너 빼기

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  const graphicErrorListener = (graphicError) => {
  	console.log(graphicError.kind);
  };
  engine.addGraphicErrorListener(graphicErrorListener);
  engine.removeGraphicErrorListener(graphicErrorListener);
  ```

- `dispatchGraphicError(graphicError)` (method, since 0.4.0): 그래픽 오류 알리기. (리스너에 그 자리에서 넘긴다, 리스너의 예외는 알리고 다음으로 간다)
  - `graphicError` object: { kind: GraphicErrorKind 의 값, name: 짓지 못한 것의 이름, error: 던져진 오류 }
- `dispatchGraphicContextEvent(graphicContextEvent)` (method, since 0.4.0): 그래픽 컨텍스트 이벤트 알리기. (리스너에 그 자리에서 넘긴다, 리스너의 예외는 알리고 다음으로 간다)
  - `graphicContextEvent` string: GraphicContextEvent 의 값.
- `enableGpuMemoryTracking()` (method, since 0.4.0): GPU 메모리 셈 켜기. (개발용, Graphic.enableGpuMemoryTracking 과 같다)

  예제: GPU 메모리 셈 켜기

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  engine.enableGpuMemoryTracking();
  console.log(engine.isGpuMemoryTrackingEnabled());
  ```

- `isGpuMemoryTrackingEnabled()` (method, since 0.4.0): GPU 메모리 셈이 켜져 있는지.
  - returns boolean: 켜져 있으면 true.

  예제: GPU 메모리 셈이 켜져 있는지 읽기

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  console.log(engine.isGpuMemoryTrackingEnabled());
  ```

- `readGpuMemoryUsage()` (method, since 0.4.0): GPU 메모리 읽기. (개발용, Graphic.readGpuMemoryUsage 와 같다)
  - returns { totalBytes: number, canvasBytes: number, kindTable: object, ownerList: Array<{ owner: string, kind: string, count: number, bytes: number }> }: 합(캔버스 몫 포함), 캔버스 몫, 종류별 { count, bytes }, 주인별 몫(큰 것부터).

  예제: 종류별 GPU 메모리 읽기

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.trackGpuMemory = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new Scene());
  const usage = engine.readGpuMemoryUsage();
  console.log(usage.kindTable.texture.bytes, usage.kindTable.renderbuffer.bytes, usage.kindTable.buffer.bytes);
  ```

- `dispatchPageEvent(pageEvent)` (method, since 0.4.0): 페이지 이벤트 알리기. (가려짐을 적고 리스너에 그 자리에서 넘긴다, 리스너의 예외는 알리고 다음으로 간다)
  - `pageEvent` string: PageEvent 의 값.
- `requestFrameCapture(frameNumber)` (method, since 0.4.0): 검증용 화면 저장 요청. (그 프레임을 다 그린 뒤 캔버스를 PNG data URL 로 넘긴다)
  - 이미 지난 번호면 이번(프레임 사이에 부르면 다음) 프레임을 저장한다.
  - 주소 쿼리로도 건다. (?capture=120,240 은 그 프레임들을 내려받기로 저장, captureName 은 파일 이름("{frame}" 은 번호), captureExit=1 은 마지막 저장 뒤 exitApplication)
    주소 쿼리로 건 찍기 모드는 결정적으로 찍게 시간이 프레임마다 1/60 초씩 간다. (실제 시각과 최대 FPS 제한을 쓰지 않는다, 러스트 판 VANILLA_CAPTURE_* 와 같다)
  - `frameNumber` number: 저장할 프레임 번호. (소수는 버리고, 이미 지났으면 지금 프레임)
  - returns Promise<string>: PNG data URL.

  예제: 30 번째 프레임을 PNG 로 받기

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new Scene());
  const capturePromise = engine.requestFrameCapture(30);
  capturePromise.then((dataUrl) => {
  	console.log(dataUrl.length);
  });
  ```

- `captureFrameIfRequested()` (method, since 0.4.0): 요청된 프레임이면 캔버스를 PNG 로 넘기기. (프레임 끝, 그린 것이 캔버스에 남아 있을 때 부른다)
- `requestFrameCapturesFromUrl()` (method, since 0.4.0): 주소 쿼리의 화면 저장 요청 걸기. (capture, captureName, captureExit)
- `static getEngine()` (static, since 0.2.0): 전역 인스턴스 반환.
  - returns Engine: 마지막으로 만든 엔진. (만든 적이 없으면 undefined)

## PageEvent (enum)

페이지 이벤트. (엔진이 리스너에 넘긴다, addPageEventListener)

- `hidden` = `hidden`: 페이지가 가려짐. (다른 탭, 앱 전환)
- `visible` = `visible`: 페이지가 다시 보임.
- `blurred` = `blurred`: 창이 포커스를 잃음. (blur)
- `focused` = `focused`: 창이 포커스를 얻음. (focus)
- `pointerDown` = `pointerDown`: 창을 누름. (pointerdown, 포커스를 알리지 않아도 누르면 창은 포커스를 가진 것이다)

## GraphicContextEvent (enum)

그래픽 컨텍스트 이벤트. (엔진이 리스너에 넘긴다, addGraphicContextEventListener)

- `lost` = `lost`: WebGL 컨텍스트를 잃음. (GPU 메모리 부족, 드라이버 재설정, 백그라운드 회수. 잃은 동안 엔진은 그리지 않고 씬 갱신만 한다)
- `restored` = `restored`: 컨텍스트가 되살아나 엔진이 기본 자원을 다시 지음. (게임이 지은 GL 객체와 3D 렌더러, 렌더 타겟은 죽었으니 이때 다시 짓는다)

## GraphicErrorKind (enum)

그래픽 오류 갈래. (엔진이 그래픽 오류 리스너에 넘기는 { kind, name, error } 의 kind, addGraphicErrorListener)

- `shaderBuildFailed` = `shaderBuildFailed`: 셰이더 프로그램을 짓지 못함. (컴파일이나 링크 실패, 같은 프로그램은 다시 알리지 않고 짓지도 않는다. 컨텍스트를 잃은 탓의 실패는 알리지 않는다)
