# gg-engine-app-development

Adopt this skill: https://proskills.md/skills/other/andygura-gg-web-engine-claude-skills-gg-engine-app-development

Page: https://proskills.md/skills/other/andygura-gg-web-engine-claude-skills-gg-engine-app-development
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: .claude/skills/gg-engine-app-development/SKILL.md
size: 98094
sha: 3b5f1e6498acb7892171e75c6e73849b2df2d335
upstream: https://github.com/andygura/gg-web-engine/blob/main/.claude/skills/gg-engine-app-development/SKILL.md
truncated: true

````text
---
name: gg-engine-app-development
description: Build an application, game, or simulation on top of gg-web-engine (as a consumer of @gg-web-engine/* npm packages). Use when the task is to write app/game code that uses the engine, not to modify the engine itself.
---

# Building apps with gg-web-engine

This skill is for writing consumer code against the published `@gg-web-engine/*` packages —
gameplay, scenes, UI glue. It does **not** cover modifying the engine's own packages; for that see
`gg-engine-core-development`, `gg-engine-visual-adapter`, or `gg-engine-physics-adapter`.

## Mental model

`GgWorld` (via `Gg3dWorld` or `Gg2dWorld`) is the root object. It composes two independent,
swappable halves that must share dimensionality (both 2D or both 3D):

- **visualScene** — a rendering backend component (`@gg-web-engine/three` for 3D,
  `@gg-web-engine/pixi` for 2D).
- **physicsWorld** — a physics backend component (3D: `@gg-web-engine/ammo` or
  `@gg-web-engine/rapier3d`; 2D: `@gg-web-engine/matter` or `@gg-web-engine/rapier2d`).

Either half can be `null`/omitted if you only need rendering or only physics. Both halves are
optional generics on `GgWorld`, so entities gracefully no-op the missing side.

An **Entity** (`Entity3d`/`Entity2d`) pairs a visual display object with a physics body and keeps
their transforms in sync each tick. Renderer, trigger, raycast vehicle, and the built-in
`GgCarEntity` are all specialized entities/components layered on top of this.

## Setup

```bash
npm install --save @gg-web-engine/core
# pick exactly one visual + one physics package of matching dimensionality:
npm install --save @gg-web-engine/three @gg-web-engine/ammo        # 3D
# or
npm install --save @gg-web-engine/pixi @gg-web-engine/rapier2d     # 2D
```

Each adapter brings its library as a regular dependency (`three` with `@types/three`, `pixi.js`,
`matter-js` with `@types/matter-js`, the Rapier compat build; Ammo is vendored), pinned to the exact
version that engine release is built against, so an app installs only `@gg-web-engine/*` packages.
If the app also imports the library itself, pin that same version so the bundle has one copy. All
`@gg-web-engine/*` packages in one app must share the same version.

## Bootstrap pattern

```typescript
import { Gg3dWorld, Pnt3, Qtrn } from '@gg-web-engine/core';
import { ThreeSceneComponent } from '@gg-web-engine/three';
import { AmmoWorldComponent } from '@gg-web-engine/ammo';

const world = new Gg3dWorld({
  visualScene: new ThreeSceneComponent(),
  physicsWorld: new AmmoWorldComponent(),
});
await world.init(); // must await before touching factories/renderers

const renderer = world.addRenderer(
  world.visualScene!.factory.createPerspectiveCamera(),
  document.getElementById('gg') as HTMLCanvasElement, // element must already exist in DOM
);
renderer.position = { x: 12, y: 12, z: 12 };
renderer.rotation = Qtrn.lookAt(renderer.camera.position, Pnt3.O);

world.addPrimitiveRigidBody({
  shape: { shape: 'BOX', dimensions: { x: 7, y: 7, z: 1 } },
  body: { bodyType: 'static' },
});

world.start(); // starts the tick clock (visual RAF loop + physics simulate())
```

The 2D equivalent (`Gg2dWorld`) uses `Shape2DDescriptor` (`BOX`/`CIRCLE`/`CAPSULE`/`CONVEX_HULL`/
`POLYGON`/`COMPOUND`) and `Point2`/`number` rotation instead of quaternions - a `COMPOUND` child's
`rotation` is a plain radians scalar rather than 3D's `Point4` quaternion. A 2D camera's `position`
is the world point at the center of the view; `camera.origin = 'top-left'` makes it the view's
top-left corner instead (see "A 2D UI layer over the game's canvas").

## Loading screen while the game starts

`LoadingScreen.show()` covers the page with the engine's loading screen (`DefaultLoadingView`:
opaque backdrop, an animated CSS 3D cube, "Loading", and a progress bar once progress is reported)
until `hide()`, which fades it out. The app decides what it covers - usually startup and level
(re)loads:

```typescript
const loading = LoadingScreen.show(); // { view?, container?, fadeOutDuration? }
const world = new Gg3dWorld({ visualScene, physicsWorld: await createPhysicsWorld() });
await world.init();
await world.loader.loadLevel(level, 'Level', { onProgress: p => loading.setProgress(p) });
// ... renderer, controllers
world.start();
loading.hide();
```

Show it before anything slow (a dynamically imported physics backend included), hide it after
`world.start()`. A game with its own loading screen - any object implementing `LoadingView`
(`element`, `setProgress`, `dispose`) - sets it once at startup with
`LoadingScreen.setDefaultView(() => new MyLoadingView())`: every `show()` without a `view` and every
`ScreenManager` without a `loadingView` then makes one from it. It takes a factory, not a view,
because hiding disposes the view. `view` on a single `show()` overrides it for that one.

Don't wrap loads that happen while the game keeps running (the next round's pieces, streamed map
chunks) - that would cover the game. Hide it in a `finally` if the startup can fail, or a failure
stays hidden behind it. A `ScreenManager` app doesn't need it: the manager shows the same default
view while a screen enters (see "Screens").

## Renderer size and resolution

`addRenderer`'s third argument (`RendererOptions` plus the adapter's own renderer options) sets the
canvas size and pixel resolution; neither needs the renderer recreated to change:

- `size` (CSS pixels): `'fullscreen'` (the default) follows the page's visible area, a function maps
  that area to a size, an `Observable<Point2>` drives it from app code, a plain `Point2` fixes it.
  The page is measured with `measureViewport()` (through `window.visualViewport` where there is one,
  which mobile browsers keep current where `innerWidth`/`innerHeight` can be stale - an iOS
  home-screen app right after a rotation), re-measured on resize and on rotation, once more
  `VIEWPORT_REMEASURE_DELAY` (300 ms) after it. App code laying out its own DOM around the game can
  subscribe to the same `viewportSize$()` instead of listening to `resize` itself.
- `forceResolution` (render pixels per CSS pixel): unset means the device's `devicePixelRatio`; a
  number fixes it; an `Observable<number>` changes it live - a game's resolution or quality setting
  feeds it, and every value is applied while the renderer is in a world (drawing buffer and any
  post-processing composer the adapter owns resized, CSS size unchanged). Until the observable's
  first value the device resolution is used, so pass a `BehaviorSubject` to start at the setting's
  value.

```typescript
const resolution$ = new BehaviorSubject(settings.hiRes ? devicePixelRatio : 1);
world.addRenderer(camera, canvas, { forceResolution: resolution$ });
resolution$.next(0.5); // later, from a settings menu
```

## Hidden tab: pausing automatically, or just reacting to it

Pass `pauseWhenHidden: true` in the `Gg3dWorld`/`Gg2dWorld` constructor args to have the world pause
itself automatically while the browser tab is hidden and resume itself when it becomes visible again
(it won't resume a world your own code already paused before the tab was hidden - that pause is left
alone). Whether or not you use that option, `world.visibility$` is an `Observable<boolean>` (`true` =
visible) you can subscribe to directly for anything else that should react to tab visibility - muting
audio, pausing polling/network calls, etc. Separately, `maxTickDelta?: number` in the same constructor
args (default 250ms, forwarded to `world.worldClock.maxTickDelta`) bounds how large a single tick's
delta can ever be, so returning to a long-backgrounded tab (if you didn't opt into
`pauseWhenHidden`) can't hand physics/animation one huge catch-up frame - pass `0` only if your app
genuinely needs unbounded ticks.

## Opt-in fixed physics timestep

By default, `world.physicsWorld.simulate()` runs once per world tick with that tick's own
(variable) delta - fine for most apps, since every adapter's own physics steppin
````

## File: README.md
upstream: https://github.com/andygura/gg-web-engine/blob/main/README.md

````text
<p align="center">
  <img src="documentation/assets/banner.png" width="100%" alt="GG Web Engine - modular 2D/3D game engine for the web"/>
</p>

<p align="center">
  <a href="https://www.npmjs.com/package/@gg-web-engine/core"><img src="https://img.shields.io/npm/v/@gg-web-engine/core?label=npm&color=22d3ee" alt="npm version"/></a>
  <a href="https://github.com/AndyGura/gg-web-engine/actions/workflows/pull_request_build.yml"><img src="https://github.com/AndyGura/gg-web-engine/actions/workflows/pull_request_build.yml/badge.svg" alt="Unit tests"/></a>
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-8b5cf6" alt="License: Apache 2.0"/></a>
  <img src="https://img.shields.io/badge/TypeScript-strict-3178c6" alt="TypeScript"/>
</p>

<p align="center">
  <b>Multiplayer physics games in the browser, with no game server.<br/>Cars and character controllers built in. TypeScript end to end.</b>
</p>

<p align="center">
  <a href="https://gg-web-demos.guraklgames.com/"><b>Live demos</b></a> •
  <a href="#-quickstart">Quickstart</a> •
  <a href="#-multiplayer-in-a-dozen-lines">Multiplayer</a> •
  <a href="#-when-to-use-it-and-when-not-to">When to use it</a> •
  <a href="#-packages">Packages</a> •
  <a href="#-architecture">Architecture</a> •
  <a href="https://andygura.github.io/gg-web-engine/">API docs</a> •
  <a href="milestones.md">Roadmap</a>
</p>

---

GG Web Engine is an open-source TypeScript game engine for the browser. Its strongest case is one the
usual browser engines leave to you: **2-8 players share one physics world over WebRTC, peer to peer**, with
ownership, late join, reconnection and replica correction built in - no game server to write or
host ([how](#-multiplayer-in-a-dozen-lines)). It also ships the parts that driving and character
games take longest to get right: a car model with engine, torque curve and gearbox, raycast
vehicles, and first-person, third-person and 2D platformer character controllers.

It does not reinvent rendering or physics. A small, strictly typed core - worlds, entities, clocks,
input, levels, networking - drives battle-tested libraries plugged in behind it:
[Three.js](https://github.com/mrdoob/three.js) or [Pixi.js](https://github.com/pixijs/pixijs) for
rendering, [Rapier](https://github.com/dimforge/rapier.js), [Ammo.js](https://github.com/kripken/ammo.js)
or [Matter.js](https://github.com/liabru/matter-js) for physics. Your game code talks to the core, so
switching to another backend of the same dimension takes one line and, apart from a few documented
gaps, needs no gameplay-code changes. Each backend keeps its own simulation behavior, so expect to
retune physics ([what differs](#-faq)). The native objects stay one property away whenever you need
them.

## ✨ Highlights

<table>
<tr>
<td width="50%" valign="top">

### 🌐 P2P multiplayer, no game server
Built for 2-8 players sharing one physics world over WebRTC, in 2D or 3D, on any physics adapter.
Ownership, possession, late join, reconnection and replica correction are built in
([how it works](#-multiplayer-in-a-dozen-lines)).

</td>
<td width="50%" valign="top">

### 🎮 Gameplay building blocks
Character controllers (2D and 3D, first/third person), raycast vehicles and a full car model with
engine and gearbox, triggers, grabbable props, cameras, animators, positional audio
([full list](#-architecture)).

</td>
</tr>
<tr>
<td valign="top">

### 🗺️ Data-driven levels
Describe a scene as JSON, register your own entity classes, wire events to behavior with blueprint
graphs, serialize live entities back. Author 3D scenes in Blender with the bundled
[exporter add-on](blender-addon/README.md).

</td>
<td valign="top">

### 🧩 Library-agnostic by design
One visual adapter + one physics adapter of matching dimensionality on top of the core. Switch from
Ammo.js to Rapier by replacing a single constructor: your code keeps compiling and running. Feel and
tuning (friction, restitution, vehicles, character sliding) differ per backend.

</td>
</tr>
<tr>
<td valign="top">

### 🛠️ Developer tooling built in
In-game console with custom commands, physics debug view, stats and per-entity performance
profiling. Use `GgStatic.instance` in a development build to turn it on for every world
([commands](#%EF%B8%8F-developer-console)).

</td>
<td valign="top">

### 🤖 AI-agent ready
Ships a [Claude Code](https://claude.com/claude-code) skill that teaches a coding agent the engine's
mental model, API and common pitfalls, so it guesses less
([install it](#-build-with-an-ai-coding-agent)).

</td>
</tr>
</table>

More of what is in the box:

- **2D and 3D worlds** sharing one set of concepts - `Gg2dWorld` and `Gg3dWorld`.
- **Automatic physics ↔ rendering sync**: an entity binds a display object to a rigid body and keeps them aligned every tick.
- **Hierarchical pausable clocks**, time scale, optional fixed physics timestep, optional auto-pause when the tab is hidden (`pauseWhenHidden`).
- **Screens and loading**: `ScreenManager` runs menu, game and pause screens as a stack of DOM layers; `LoadingScreen.show()`/`hide()` covers startup or a level load with the built-in loading screen, or with your own.
- **Streaming large maps**: `MapGraph3dEntity` loads and disposes map chunks by proximity.
- **Reactive API** on [RxJS](https://github.com/ReactiveX/rxjs): ticks, input, collisions and world events are observables.
- **Strict TypeScript throughout**; annotate the world as `TypedGg3dWorld`/`TypedGg2dWorld` to get the native types of whichever libraries you plugged in ([how](#-faq)).

## 🚀 Quickstart

The fastest start is a starter template: a Vite + TypeScript project with a level, controls and a
camera already wired, ready to grow into a game.

```bash
npx degit AndyGura/gg-web-engine/templates/3d-character my-game   # or 2d-platformer, multiplayer-cars
cd my-game && npm install && npm run dev
```

See [`templates/`](templates/README.md) for what each one contains. To add the engine to an existing
project instead:

```bash
npm install @gg-web-engine/core @gg-web-engine/three @gg-web-engine/rapier3d
```

Add a canvas to the page (`<canvas id="gg"></canvas>`, and `body { margin: 0; }`), then:

```typescript
import { Gg3dWorld, Pnt3, Qtrn, TypedGg3dWorld } from '@gg-web-engine/core';
import { ThreeGgWorld, ThreeSceneComponent } from '@gg-web-engine/three';
import { Rapier3dGgWorld, Rapier3dWorldComponent } from '@gg-web-engine/rapier3d';

// one world = clock + visual scene + physics world
const world: TypedGg3dWorld<ThreeGgWorld, Rapier3dGgWorld> = new Gg3dWorld({
  visualScene: new ThreeSceneComponent(),
  physicsWorld: new Rapier3dWorldComponent(), // or: new AmmoWorldComponent()
});
await world.init();

// viewport and camera
const renderer = world.addRenderer(
  world.visualScene.factory.createPerspectiveCamera(),
  document.getElementById('gg')! as HTMLCanvasElement,
);
renderer.position = { x: 12, y: 12, z: 12 };
renderer.rotation = Qtrn.lookAt(renderer.camera.position, Pnt3.O);

// static floor
world.addPrimitiveRigidBody({
  shape: { shape: 'BOX', dimensions: { x: 7, y: 7, z: 1 } },
  body: { bodyType: 'static' },
});

// drop a 1 kg cube twice a second
const spawnTimer = world.createClock(true);
spawnTimer.tickRateLimit = 2;
spawnTimer.tick$.subscribe(() => {
  const cube = world.addPrimitiveRigidBody({
    shape: { shape: 'BOX', dimensions: { x: 1, y: 1, z: 1 } },
    body: { mass: 1 },
  });
  cube.position = { x: Math.random() * 5 - 2.5, y: Math.random() * 5 - 2.5, z: 10 };
  setTimeout(() => world.removeEntity(cube, true), 30000);
});

world.start();
```

<p align="center">
  <img src="documentation/assets/example.gif" alt="Cubes falling on a platform"/>
</p>

> 3D worlds are always Z-up: `{x, y}` is the ground plane, `+Z` points to the sky.

### The same scene as data

Levels can be plain JSON, loaded with the world's `LevelLoader`. Built-in classes cover primitives,
triggers, cameras, lights, environment, players, GLB models, cars, map graphs and sounds; your
````
