# game/gamescene (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/game/gamescene/

Common base scene for games.

## ScreenFadeHold extends Object

A hold that keeps the screen fade dark. (Same as Rust ScreenFadeHold)
- Returned by fadeScreen's onDark or received by fadeScreenWithHold's onDark. The screen stays dark until release is called.

Example: Receive a hold when fully dark and stay dark until it is released

```js
import { ScreenFadeHold } from "./build/vanilla.js";

const screenFadeHold = new ScreenFadeHold();
console.log(screenFadeHold.isReleased());
screenFadeHold.release();
console.log(screenFadeHold.isReleased());
```

- `constructor()` (constructor, since 0.4.0): Constructor. (Not released yet)
- `release()` (method, since 0.4.0): Releases the hold. (The overlay brightens)
- `isReleased()` (method, since 0.4.0): Whether it is released.
  - returns boolean: True if release was called.

## GameScene extends Scene

Common base scene for games.
- Loading screen (center image + gauge + tap to skip).
  Change the colors with setLoadingColors and the whole drawing with setLoadingDrawer. By default the gauge shows the elapsed minimum display time,
  and once progress is reported with setLoadingProgress or trackAssetLoader it smoothly follows that progress. (LoadingProgress)
- Developer tools (DevTools).
- Touch input routing (TouchRecognizer, ignored while DevTools captures input).
- Safe area node + env(safe-area-inset-*) calculation.
- Detects viewSize changes automatically → calls layout again.
- Clears the canvas background.
- Screen fade (fadeScreen, blocks input while dark).
- UI hit test (isUserInterfaceAt) and passing only the input the UI did not take to play (setPlayInputHandler, play area coordinates).
  Instead of a handler, input can also be collected and taken out later. (setPlayInputEnabled, takePlayInputs)
- Safe area insets can be set directly. (setSafeAreaInsets, CSS pixels. If not set, the view manager's values)
- Keeps the fixed-side length of the play area excluding the safe area constant (setPlayAreaReference).

Subclass hooks:
- loadAssets(): after calling super, loads its own assets asynchronously.
- layout(): after calling super, updates its own content layout.

Example: Attaching text to the safe area node and receiving play input

```js
import { Engine, EngineConfiguration, GameScene, WorldNode, Text, Pivot, Vector2 } from "./build/vanilla.js";

class MainScene extends GameScene {
	constructor() {
		super();
		this.setLoadingMinDurationMs(0);
		this.setSceneBackgroundColor("#151821");
	}

	initialize(engine) {
		super.initialize(engine);
		const titleNode = new WorldNode();
		titleNode.setPivot(Pivot.topLeft);
		titleNode.setRect(40, 40, 600, 48);
		const text = titleNode.addComponent(Text);
		text.setText("Tap the play area");
		text.setFontSize(32);
		this.getSafeAreaNode().addChild(titleNode);

		// Only presses the UI did not take arrive here, in play area coordinates.
		this.setPlayInputHandler({
			press: (position) => {
				console.log("play press", position.x, position.y);
				this.fadeScreen(() => {
					text.setText("Faded at " + Math.round(position.x) + ", " + Math.round(position.y));
				});
			},
		});
	}
}
const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(1280, 720);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.2.1): Constructor.
- `setViewScaleMode(viewScaleMode)` (method, since 0.2.1): Sets the ViewScaleMode. Can be set freely per project.
  - Default is ViewScaleMode.none. Can be called anywhere before / after engine startup.
  - If the engine is already attached at call time, it is applied to viewManager immediately,
    otherwise it is applied all at once in initialize().
  - `viewScaleMode` string: View scale mode. (a ViewScaleMode value, default ViewScaleMode.none)
- `getViewScaleMode()` (method, since 0.2.1): Returns the current ViewScaleMode.
  - returns string: The current view scale mode. (a ViewScaleMode value)
- `setLoadingImageUrl(url)` (method, since 0.2.1): Sets the loading screen center image URL. (shows only the gauge without an image if empty string)
  - `url` string: URL of the image drawn at the center of the loading screen. (If empty, only the gauge is drawn without an image)
- `setLoadingMinDurationMs(milliseconds)` (method, since 0.2.1): Sets the loading screen minimum display time (ms).
  - `milliseconds` number: Minimum time to show the loading screen. (milliseconds, default 3000, skipped at once when the screen is pressed)
- `setLoadingDrawer(drawer)` (method, since 0.4.0): Sets the loading screen drawing function. (null for the default drawing: loading image at the center + gauge below)
  - The engine fills the canvas with the outside color and the view with the background color, applies the view coordinate system, then calls drawer(graphic, viewSize, progress, elapsedSeconds).
    progress is the displayed progress (0 ~ 1, the elapsed minimum display time if nothing was reported), and elapsedSeconds is the seconds since loading started.
  - It is drawn even before images and fonts are loaded, so draw with shapes and system fonts.
  - `drawer` ((graphic: Graphic, viewSize: Vector2, progress: number, elapsedSeconds: number) => void) | null: Loading screen drawing function. (Receives graphic, viewSize, progress, elapsedSeconds, null for the default drawing)
- `getLoadingDrawer()` (method, since 0.4.0): Returns the loading screen drawing function. (null if none)
  - returns Function | null: Loading screen drawing function. (null if not set)
- `setLoadingColors(backgroundColor, barBackColor, barFillColor, outsideColor = backgroundColor)` (method, since 0.4.0): Sets the loading screen colors. (A Color or color text such as "#rrggbb", defaults are a black background, #333333 gauge background, #ffffff gauge)
  - outsideColor is the color outside the view (the rest of the canvas). If omitted, it is the same as the background color.
  - `backgroundColor` Color | string: View background color. (A Color or color text, default black)
  - `barBackColor` Color | string: Gauge background color. (default #333333)
  - `barFillColor` Color | string: Gauge fill color. (default #ffffff)
  - `outsideColor` Color | string: Color outside the view (the rest of the canvas). (The background color if omitted)
- `setLoadingOutsideColor(outsideColor)` (method, since 0.4.0): Sets the loading screen color outside the view (the rest of the canvas). (Changes only the fourth value of setLoadingColors)
  - `outsideColor` Color | string: Color outside the view (the rest of the canvas). (A Color or color text)
- `hasLoadingDrawer()` (method, since 0.4.0): Whether a loading screen drawing function is set.
  - returns boolean: True if a loading screen drawing function is set.
- `isLoadTouchedToSkip()` (method, since 0.4.0): Whether the loading screen was tapped to skip.
  - returns boolean: True if the loading screen was tapped to skip the minimum display time.
- `getDevTools()` (method, since 0.4.0): Returns the developer tools. (null before initialize or when EngineConfiguration.useDevTools is off)
  - returns DevTools | null: Developer tools. (null before initialize or when EngineConfiguration.useDevTools is off)
- `setSafeAreaInsets(insets)` (method, since 0.4.0): Sets the safe area insets directly. (CSS pixels { top, right, bottom, left }, if null reads the view manager's getSafeAreaInsets)
  - `insets` { top: number, right: number, bottom: number, left: number } | null: Top, right, bottom, left insets. (CSS pixels, if null reads the view manager's getSafeAreaInsets)
- `static calculateSafeAreaRect(viewSize, targetResolutionScale, insets)` (static, since 0.4.0): Calculates the safe area. (static, divides CSS pixel insets by the view scale and subtracts them from the view area)
  - `viewSize` Vector2: View size. (view units)
  - `targetResolutionScale` number: View scale. (Insets are divided by this to convert to view units, 1 if 0 or less)
  - `insets` { top: number, right: number, bottom: number, left: number }: CSS pixels.
  - returns Rect: Safe area rectangle. (view coordinates, width and height are 0 or more)
- `setLoadingProgress(progress)` (method, since 0.4.0): Reports loading progress. (0 ~ 1, never decreases. After reporting, the gauge follows this value instead of the elapsed time)
  - `progress` number: Progress to report. (0 ~ 1, never less than what was reported before)
- `getLoadingProgress()` (method, since 0.4.0): Returns the loading progress. (The reported amount and the displayed amount that smoothly follows it)
  - returns LoadingProgress: Loading progress. (The reported amount and the displayed amount that smoothly follows it)
- `trackAssetLoader(assetLoader)` (method, since 0.4.0): Hands over an asset loader. (Every frame the loading screen reports the finished count / total count of what was handed over as progress)
  - `assetLoader` AssetLoader: The asset loader whose progress the loading screen follows.
- `updateTrackedAssetLoaderProgress()` (method, since 0.4.0): Reports the progress of the handed-over asset loaders. (Does nothing if none were handed over)
- `getSafeAreaNode()` (method, since 0.2.1): Returns the safe area node. (Subclasses attach child content here)
  - returns WorldNode: Safe area node. (Attach the subclass's content here)
- `getSafeAreaRect()` (method, since 0.2.1): Returns the last calculated safe area rect.
  - returns Rect: The last calculated safe area rect. (view coordinates)
- `async load(engine)` (method, since 0.2.1): Asynchronous load.
  - Calls the loadAssets() hook + guarantees the minimum display time.
  - Time is measured with the engine clock (TimeManager.getRealtimeSinceStartup). If the engine clock has not started yet (before the first frame, 0), it is measured from the time of the first loading screen frame.
  - Tapping the screen skips right away. drawOnLoad checks the tap every frame through engine input (InputManager.isTouchPressed).
    (Same clock and same input as the Rust edition)
  - `engine` Engine: The engine loading the scene.
- `async loadAssets()` (method, since 0.2.1): Asset loading hook.
  - Subclasses override it to load their own assets asynchronously. Calling super is required.
- `drawOnLoad(graphic)` (method, since 0.2.1): Draws the loading screen. (The engine calls it every frame while isLoaded() === false)
  - Outside-color canvas + background-color view + (the drawing function, or if none, the center loading image + bottom gauge).
  - `graphic` Graphic: Graphic to draw with.
- `initialize(engine)` (method, since 0.2.1): Initialization.
  - `engine` Engine: The engine that loaded the scene.
- `resize(canvasNativeSize)` (method, since 0.2.1): Screen size changed.
  - `canvasNativeSize` Vector2: New size of the canvas element. (CSS pixels)
- `layout()` (method, since 0.2.1): Layout.
  - Subclasses call super.layout() and then update their own content layout.
- `computeSafeAreaRect()` (method, since 0.2.1): Calculates the safe area. (in the view coordinate system)
  - returns Rect: Safe area rectangle. (view coordinates, width and height are 0 or more)
- `tick(timeDelta)` (method, since 0.2.1): Update.
  - Detects viewSize changes → calls layout again automatically.
    (Corrected every tick because the resize event alone can miss changes,
     such as when 100vh changes dynamically as the mobile address bar shows or hides.)
  - Handles the DevTools tick.
  - `timeDelta` number: Time since the last frame. (Seconds)
- `isDevToolsCapturingInput()` (method, since 0.2.1): Whether DevTools is taking the input.
  - returns boolean: True if the developer tools panel is visible and the pointer is over it.
- `getTouchRaycaster()` (method, since 0.4.0): Returns the touch raycaster. (the TouchRecognizer that the touch hooks pass to nodes; the scene's default passing is turned off and this one is used)
  - returns TouchRecognizer: The TouchRecognizer that the touch hooks pass to. (undefined before initialize)
- `touchPress(viewInputPosition)` (method, since 0.2.1): touchPress.
  - `viewInputPosition` Vector2: Press position. (view coordinates)
- `touchMove(viewInputPosition)` (method, since 0.2.1): touchMove.
  - `viewInputPosition` Vector2: Moved position. (view coordinates)
- `touchRelease(viewInputPosition)` (method, since 0.2.1): touchRelease.
  - `viewInputPosition` Vector2: Release position. (view coordinates)
- `touchCancel(viewInputPosition)` (method, since 0.2.1): touchCancel.
  - `viewInputPosition` Vector2: Position at cancel. (view coordinates)
- `touchWheel(viewInputPosition, wheelDelta)` (method, since 0.2.1): touchWheel. (Passes it to the frontmost scroll view at that position, true if a view took it)
  - An overriding game scene that passes the wheel to the game (map zoom and so on) only when super.touchWheel is false does not overlap with window scrolling.
  - `viewInputPosition` Vector2: Position where the wheel was rolled. (view coordinates)
  - `wheelDelta` Vector2: Wheel amount accumulated this frame. (deltaX, deltaY of WheelEvent)
  - returns boolean: True if a scroll view at that position took the wheel.
- `preDraw(graphic)` (method, since 0.2.1): preDraw. Fills the whole canvas with sceneBackgroundColor (including the area outside the safe area).
  - `graphic` Graphic: Graphic to draw with.
- `postDraw(graphic)` (method, since 0.2.1): postDraw. Draws the fade overlay and DevTools on top of the screen.
  - `graphic` Graphic: Graphic to draw with.
- `fadeScreen(onDark)` (method, since 0.4.0): Fades to dark and back.
  - When fully dark, calls onDark. If it returns a Promise, the screen stays dark until it settles (even on failure), and if it returns a ScreenFadeHold, until the hold is released. Then it brightens.
  - While the overlay is up (darkening, waiting, brightening), presses and wheel input are not received.
  - If already fading, the call is ignored and returns false.
  - `onDark` Function | null: () => void | Promise | ScreenFadeHold
  - returns boolean: Whether it started.
- `fadeScreenWithHold(onDark)` (method, since 0.4.0): The hold form of fading to dark and back. (Same as Rust fade_screen_with_hold)
  - When fully dark, passes a new ScreenFadeHold to onDark and stays dark until that hold is released.
  - If already fading, the call is ignored and returns false.
  - `onDark` function(ScreenFadeHold): void: Function called with the hold when the screen is fully dark.
  - returns boolean: Whether it started.
- `isScreenFading()` (method, since 0.4.0): Whether a fade is in progress. (darkening, waiting for onDark, or brightening)
  - returns boolean: True while darkening, waiting for onDark, or brightening.
- `setScreenFadeColor(color)` (method, since 0.4.0): Sets the color of the fade overlay. (default black)
  - `color` Color | string: Color of the fade overlay. (A Color or color text, default black)
- `setScreenFadeSeconds(seconds)` (method, since 0.4.0): Sets the time to darken and to brighten. (seconds, default 0.35, immediate if 0)
  - `seconds` number: Time to darken, and also to brighten. (seconds, default 0.35, immediate if 0)
- `getScreenFadeAlpha()` (method, since 0.4.0): Opacity of the fade overlay. (0 ~ 1)
  - returns number: Opacity of the fade overlay. (0 ~ 1)
- `updateScreenFade()` (method, since 0.4.0): Updates the overlay. (Called by tick, advances with unscaled time so it runs even when play is paused, up to 0.1 seconds per frame)
- `drawScreenFade(graphic)` (method, since 0.4.0): Draws the fade overlay. (Covers the whole canvas including the safe area insets)
  - `graphic` Graphic: Graphic to draw with.
- `isUserInterfaceAt(viewPosition)` (method, since 0.4.0): Whether there is UI (a pressable node: a button, a window's dimmer and panel, a scroll view) at that position. (view coordinates)
  - `viewPosition` Vector2: Position to test. (View coordinates)
  - returns boolean: True if there is a pressable UI node at that position.
- `setPlayInputHandler(playInputHandler)` (method, since 0.4.0): Sets the play input handler. (Passes presses the UI did not take, their moves and releases (including cancel), and the wheel outside the UI in play area coordinates, null to pass nothing)
  - The play area is the safe area rect (getSafeAreaRect). Its top left is 0, 0.
  - Presses and the wheel are not passed during a fade. Nothing is passed while the developer tools capture input.
  - `playInputHandler` object | null: { press?(position), move?(position), release?(position), wheel?(position, wheelDelta) }
- `setPlayInputEnabled(isPlayInputEnabled)` (method, since 0.4.0): Turns on play input collection. (Collects input instead of a handler, to be taken out with takePlayInputs, turning it off discards what was collected)
  - `isPlayInputEnabled` boolean: If true, collects play input. (If false, discards what was collected)
- `takePlayInputs()` (method, since 0.4.0): Takes the collected play input. ({ kind, position, wheelDelta } in arrival order, taking empties it)
  - returns Array<{ kind: string, position: Vector2, wheelDelta: Vector2 | null }>: Collected play input. (In arrival order, kind is press, move, release, wheel, taking empties it)
- `convertViewToPlayArea(viewPosition)` (method, since 0.4.0): View coordinates → play area coordinates. (The safe area's top left is 0, 0)
  - `viewPosition` Vector2: Position to convert. (view coordinates)
  - returns Vector2: Play area coordinates. (The safe area's top left is 0, 0)
- `dispatchPlayInput(kind, viewPosition, wheelDelta)` (method, since 0.4.0): Dispatches play input. (kind is press, move, release, wheel, not passed if the handler lacks that function)
  - `kind` string: Input kind. (press, move, release, wheel)
  - `viewPosition` Vector2: Input position. (view coordinates)
  - `wheelDelta` Vector2 | null: Wheel amount. (null unless wheel)
- `releasePlayPress(viewPosition)` (method, since 0.4.0): Ends a press that went to play. (release and cancel)
  - `viewPosition` Vector2: Release position. (view coordinates)
- `setPlayAreaReference(fixedLength, isLandscape)` (method, since 0.4.0): Sets the play area reference. (Enlarges the reference resolution so the fixed-side length of the play area excluding the safe area insets is always fixedLength)
  - The engine fits the whole canvas length to the reference resolution, but the canvas also covers the safe area insets. The reference resolution is enlarged by that much.
    (canvas length : length excluding the safe area insets = reference resolution length : fixedLength)
  - If isLandscape the width is the fixed side, otherwise the height. The view scale mode is set to match. (width fixed stretchWidthExpandHeight, height fixed stretchHeightExpandWidth)
  - Pass the safe area sides to ignore with ViewManager.setIgnoredSafeAreaSides. A fixedLength of 0 turns it off. (The reference resolution is left as is)
  - `fixedLength` number: Fixed-side length of the play area excluding the safe area insets. (reference resolution units, 0 turns it off)
  - `isLandscape` boolean: If true the width is the fixed side, if false the height.
- `getPlayAreaFixedLength()` (method, since 0.4.0): Fixed-side length of the play area. (0 if not used)
  - returns number: Fixed-side length of the play area. (0 if not used)
- `applyPlayAreaReference()` (method, since 0.4.0): Applies the play area reference to the reference resolution. (Computed only from the canvas and inset sizes, so repeated calls give the same result, left untouched if unchanged)
- `static calculatePlayAreaReferenceLength(fixedLength, isLandscape, canvasNativeSize, safeAreaInsets, insetScale)` (static, since 0.4.0): Computes the reference resolution length for the play area reference. (0 if it cannot be computed)
  - `fixedLength` number: Fixed-side length of the play area excluding the safe area insets. (reference resolution units)
  - `isLandscape` boolean: If true the width is the fixed side, if false the height.
  - `canvasNativeSize` Vector2: Size of the canvas element. (CSS pixels)
  - `safeAreaInsets` object: { top, right, bottom, left } (view coordinates)
  - `insetScale` number: Scale from view coordinates → canvas units.
  - returns number: Fixed-side length of the reference resolution. (0 if it cannot be computed)
