@gwenjs/core API Reference
pnpm add @gwenjs/core
@gwenjs/core — Engine
The flat import. Engine bootstrap, shared types, WASM utilities, tween.
Key exports: createEngine, useEngine, GwenContextError, GwenPlugin (type), GwenEngine (type), GwenProvides (type), GwenRuntimeHooks (type), createLogger, initWasm, tween utilities.
Usage:
import { createEngine, useEngine, createLogger } from '@gwenjs/core'
import { useTween } from '@gwenjs/core'Engine
createEngine(options)
Signature:
function createEngine(options: GwenEngineOptions): GwenEngineDescription. Creates and initializes the GWEN engine with the provided configuration. This is the foundation of your game/app.
Parameters:
| Param | Type | Description |
|---|---|---|
| options | GwenEngineOptions | Engine configuration (scenes, plugins, etc.) |
Returns: GwenEngine — the initialized engine instance.
Example:
const engine = await createEngine({
maxEntities: 10_000,
variant: 'physics2d',
debug: true,
})useEngine()
Signature:
function useEngine(): GwenEngineDescription. Returns the current engine instance inside a system setup or composable. Must be called during system initialization.
Returns: GwenEngine — the active engine.
Example:
const MySystem = defineSystem('MySystem', () => {
const engine = useEngine()
console.log(engine.deltaTime)
})useTween(options)
Signature:
function useTween<T>(options: {
duration: number
easing?: string
loop?: boolean
yoyo?: boolean
}): TweenHandle<T>Description. Creates an animation tween. Returns a handle with methods to play, pause, reset, queue follow-ups, and register completion callbacks.
Parameters:
| Param | Type | Description |
|---|---|---|
| options.duration | number | Duration in seconds |
| options.easing | string | Easing function name (optional) |
| options.loop | boolean | Loop animation (optional) |
| options.yoyo | boolean | Reverse animation on loop (optional) |
Returns: TweenHandle<T> — tween controller with methods: .play({ from, to }), .pause(), .reset(), .to({ value, duration }), .onComplete(cb), .onLoop(cb), and properties: .value, .playing.
Example:
const opacity = useTween<number>({ duration: 0.5, easing: 'easeInOut' })
onUpdate(() => {
if (!opacity.playing) {
opacity.play({ from: 0, to: 1 })
}
mesh.material.opacity = opacity.value
})@gwenjs/core/system
System definition and frame-loop composables.
Exports: defineSystem, onUpdate, onBeforeUpdate, onAfterUpdate, onRender, useQuery, useService, useWasmModule
Usage:
import { defineSystem, onUpdate, onBeforeUpdate, onAfterUpdate, onRender } from '@gwenjs/core/system'
import { useQuery, useService, useWasmModule } from '@gwenjs/core/system'Systems
defineSystem(setup)
Signature:
function defineSystem(setup: () => void): GwenPluginDescription. Defines a system that runs once during initialization. Use lifecycle hooks and queries inside setup.
Parameters:
| Param | Type | Description |
|---|---|---|
| setup | function | Setup function called once at initialization |
Returns: GwenPlugin — plugin for scene registration.
Example:
export const moveSystem = defineSystem(function moveSystem() {
const query = useQuery([Position, Velocity])
onUpdate((dt) => {
for (const id of query) {
Position.x[id] += Velocity.x[id] * dt
Position.y[id] += Velocity.y[id] * dt
}
})
})useQuery(components)
Signature:
function useQuery(components: ComponentDef[]): LiveQueryDescription. Creates a live query that iterates over all entities with the specified components. The query updates automatically when entities match/unmatch.
Parameters:
| Param | Type | Description |
|---|---|---|
| components | ComponentDef[] | Components to query for |
Returns: LiveQuery — an iterable set of matching entities.
Example:
const enemies = useQuery([Position, EnemyTag])
onUpdate(() => {
for (const id of enemies) {
Position.x[id] += 1
}
})useService(name)
Signature:
function useService(name: string): anyDescription. Returns a service registered by a plugin.
Parameters:
| Param | Type | Description |
|---|---|---|
| name | string | Service name |
Returns: any — the service instance.
Example:
const physics = useService('physics');useWasmModule(name)
Signature:
function useWasmModule(name: string): anyDescription. Returns a WASM module loaded by a plugin.
Parameters:
| Param | Type | Description |
|---|---|---|
| name | string | WASM module name |
Returns: any — the WASM module handle.
@gwenjs/core/actor
Actor definition, instance lifecycle, and all actor composables.
Exports: defineActor, onStart, onDestroy, onEvent, onUpdate, onBeforeUpdate, onAfterUpdate, onRender, definePrefab, defineEvents, emit, useActor, useComponent, usePrefab, useEntityId, useTransform, defineLayout, useLayout, placeActor, placeGroup, placePrefab
Usage:
import { defineActor, onStart, onDestroy, onUpdate, onBeforeUpdate, onAfterUpdate, onRender } from '@gwenjs/core/actor'
import { definePrefab, defineEvents, emit, useActor, useComponent, usePrefab } from '@gwenjs/core/actor'
import { useTransform, defineLayout, useLayout, placeActor, placeGroup, placePrefab } from '@gwenjs/core/actor'Actors
defineActor(prefab, factory)
Signature:
function defineActor<Props = void>(
prefab: PrefabDefinition,
factory: (props?: Props) => Record<string, unknown>
): ActorDefDescription. Defines an actor — an entity template with lifecycle hooks and a public API. The factory runs once per spawned instance; register lifecycle hooks (onStart, onUpdate, onDestroy, onEvent) inside it. The returned object becomes the actor's public API.
Parameters:
| Param | Type | Description |
|---|---|---|
prefab | PrefabDefinition | Component set and defaults, defined with definePrefab() |
factory | (props?) => object | Runs once per spawn — register lifecycle hooks here, return public API |
Returns: ActorDef — use ActorDef._plugin to spawn and despawn instances.
Example:
import { defineActor, definePrefab, onStart, onDestroy, useEntityId } from '@gwenjs/core/actor'
const EnemyPrefab = definePrefab([
{ def: Position, defaults: { x: 0, y: 0 } },
{ def: Health, defaults: { hp: 100 } },
])
export const EnemyActor = defineActor(EnemyPrefab, (props: { hp: number }) => {
const entityId = useEntityId()
onStart(() => {
Health.hp[entityId] = props.hp
})
onDestroy(() => {
console.log('Enemy destroyed')
})
return {
takeDamage: (n: number) => { Health.hp[entityId] -= n },
}
})
// Spawn and despawn via _plugin:
await engine.use(EnemyActor._plugin)
const id = EnemyActor._plugin.spawn({ hp: 50 })
EnemyActor._plugin.despawn(id)useActor(ActorDef)
Signature:
function useActor(def: ActorDef): voidDescription. Registers an actor for use within another actor (composition).
Returns: void
useComponent(ComponentDef)
Signature:
function useComponent<T = {}>(def: ComponentDef<T>): voidDescription. Registers a component for use in the current actor during setup.
Returns: void
Example:
export const PlayerActor = defineActor(PlayerPrefab, () => {
const health = useComponent(Health)
onStart(() => {
console.log('hp:', health.hp)
})
})usePrefab(PrefabDef)
Signature:
function usePrefab(def: PrefabDef): () => EntityDescription. Returns a spawn function for a prefab.
Returns: () => Entity — function to spawn the prefab.
Example:
const spawnBullet = usePrefab(BulletPrefab);
const bullet = spawnBullet();placeActor(def, overrides?)
Signature:
function placeActor(def: ActorDef, overrides?: Record<string, any>): EntityDescription. Immediately spawns an actor in the current scene.
Parameters:
| Param | Type | Description |
|---|---|---|
| def | ActorDef | Actor definition |
| overrides | object | Component property overrides |
Returns: Entity — the spawned entity.
Example:
const enemy = placeActor(Enemy, { health: { hp: 50 } });placePrefab(def, overrides?)
Signature:
function placePrefab(def: PrefabDef, overrides?: Record<string, any>): EntityDescription. Immediately spawns a prefab in the current scene.
Returns: Entity — the spawned entity.
placeGroup(actors)
Signature:
function placeGroup(actors: (ActorDef | () => ActorDef)[]): Entity[]Description. Spawns multiple actors at once.
Parameters:
| Param | Type | Description |
|---|---|---|
| actors | array | Array of actor definitions or factories |
Returns: Entity[] — array of spawned entities.
Prefabs
definePrefab(options)
Signature:
function definePrefab(options: {
name: string;
components: ComponentDef[];
defaults?: Record<string, any>;
}): PrefabDefDescription. Defines a reusable entity template (prefab) with predefined components and default values.
Parameters:
| Param | Type | Description |
|---|---|---|
| options.name | string | Unique prefab name |
| options.components | ComponentDef[] | Components to include |
| options.defaults | object | Default component property values |
Returns: PrefabDef — prefab definition.
Example:
const BulletPrefab = definePrefab({
name: 'Bullet',
components: [Transform, Velocity],
defaults: {
transform: { x: 0, y: 0 },
velocity: { x: 0, y: 0 }
}
});Lifecycle Hooks
onStart(cb)
Signature:
function onStart(cb: () => void): voidDescription. Registers a callback to run when the engine starts or a scene is entered.
Returns: void
onDestroy(cb)
Signature:
function onDestroy(cb: () => void): voidDescription. Registers a callback to run when the engine stops or a scene is exited.
Returns: void
onEvent(type, handler)
Signature:
function onEvent<T = any>(type: string, handler: (payload: T) => void): voidDescription. Registers a handler for custom events emitted with emit().
Parameters:
| Param | Type | Description |
|---|---|---|
| type | string | Event type identifier |
| handler | function | Handler receiving the event payload |
Returns: void
Example:
onEvent('player-hit', (damage) => {
console.log('Player took', damage, 'damage');
});onUpdate(cb)
Signature:
function onUpdate(cb: (deltaTime: number) => void): voidDescription. Registers a callback to run every frame during the update phase.
Parameters:
| Param | Type | Description |
|---|---|---|
| cb | function | Callback receiving deltaTime in seconds |
Returns: void
Example:
onUpdate((dt) => {
console.log('Frame time:', dt);
});onBeforeUpdate(cb)
Signature:
function onBeforeUpdate(cb: () => void): voidDescription. Registers a callback to run before the main update phase.
Returns: void
onAfterUpdate(cb)
Signature:
function onAfterUpdate(cb: () => void): voidDescription. Registers a callback to run after the main update phase.
Returns: void
onRender(cb)
Signature:
function onRender(cb: () => void): voidDescription. Registers a callback to run during the render phase.
Returns: void
Events
defineEvents(map)
Signature:
function defineEvents(map: Record<string, any>): EventDefDescription. Defines event types for your game.
Parameters:
| Param | Type | Description |
|---|---|---|
| map | object | Event type definitions |
Returns: EventDef
Example:
const Events = defineEvents({
'player-hit': { damage: Number },
'level-complete': { time: Number }
});emit(event, payload)
Signature:
function emit(event: string, payload?: any): voidDescription. Emits a custom event to all listeners registered with onEvent().
Parameters:
| Param | Type | Description |
|---|---|---|
| event | string | Event type identifier |
| payload | any | Event payload (optional) |
Returns: void
Example:
emit('player-hit', { damage: 10 });UI & Layout
defineLayout(name, setup)
Signature:
function defineLayout(name: string, setup: (ctx: LayoutContext) => void): LayoutDefDescription. Defines a persistent UI layer that overlays the game.
Parameters:
| Param | Type | Description |
|---|---|---|
| name | string | Unique layout name |
| setup | function | Setup function for UI initialization |
Returns: LayoutDef
Example:
const HUD = defineLayout('HUD', (setup) => {
// Initialize UI elements
});useLayout()
Signature:
function useLayout(): LayoutDescription. Returns the current layout context. Use to add/remove UI elements.
Returns: Layout
useEntityId()
Signature:
function useEntityId(): bigintDescription. Returns the ECS entity ID of the actor currently being set up. The value is a bigint that uniquely identifies this actor instance for its entire lifetime (from spawn to despawn).
Must be called during the setup phase of a defineActor() factory — i.e. at the top level of the factory function, not inside onStart, onUpdate, or other callbacks.
Returns: bigint — the entity ID of the actor being spawned.
Throws: If called outside an active defineActor() factory context.
Example — singleton actor (static key preferred):
import { defineActor } from '@gwenjs/core/actor'
export const HudActor = defineActor(HudPrefab, () => {
// Only one HUD exists — a static key is clearest
const hud = useHTML('hud', 'score')
})Example — multiple instances (unique key per actor):
import { defineActor, useEntityId } from '@gwenjs/core/actor'
export const EnemyActor = defineActor(EnemyPrefab, () => {
const id = useEntityId()
const label = useHTML('ui', String(id)) // unique slot per enemy
})Example — inside a composable:
import { useEntityId } from '@gwenjs/core/actor'
import { useService } from '@gwenjs/core/system'
import { onCleanup } from '@gwenjs/core'
export function useSprite(src: string): SpriteHandle {
const id = useEntityId()
const service = useService('renderer:canvas')
const sprite = service.allocateSprite(String(id), src)
onCleanup(() => sprite.destroy())
return sprite
}useTransform()
Signature:
function useTransform(): TransformDescription. Returns the transform component of the current entity.
Returns: Transform — with position, rotation, scale properties.
Example:
const transform = useTransform();
transform.x += 10;@gwenjs/core/scene
Scene and router definition.
Exports: defineScene, defineSceneRouter, useSceneRouter
Usage:
import { defineScene, defineSceneRouter, useSceneRouter } from '@gwenjs/core/scene'Scenes
defineScene(options)
Signature:
function defineScene(options: {
name: string;
systems?: SystemDef[];
actors?: ActorDef[];
}): SceneDefDescription. Defines a scene with systems and initial actors.
Parameters:
| Param | Type | Description |
|---|---|---|
| options.name | string | Unique scene name |
| options.systems | SystemDef[] | Systems to run in this scene |
| options.actors | ActorDef[] | Initial actors to spawn |
Returns: SceneDef — scene definition.
Example:
const GameScene = defineScene({
name: 'Game',
systems: [PhysicsSystem, InputSystem],
actors: [Player, Enemy]
});defineSceneRouter(options)
Signature:
function defineSceneRouter(options: {
initial: string;
routes: Record<string, { scene: SceneDef; on: Record<string, string> }>;
}): SceneRouterDefDescription. Defines a scene router for managing scene transitions.
Returns: SceneRouterDef
Example:
defineSceneRouter({
initial: 'menu',
routes: {
menu: { scene: MenuScene, on: { PLAY: 'game' } },
game: { scene: GameScene, on: { MENU: 'menu' } },
},
})useSceneRouter(routerDef)
Signature:
function useSceneRouter<TRoutes>(
routerDef: SceneRouterDefinition<TRoutes>
): SceneRouterHandle<TRoutes>Description. Returns the runtime handle for a scene router. Call .send() to trigger transitions. Must be called inside an active engine context (system, actor, or scene lifecycle hook).
Parameters:
| Param | Type | Description |
|---|---|---|
| routerDef | SceneRouterDefinition | Router created by defineSceneRouter() |
Returns: SceneRouterHandle — with methods .send(event, params?), .can(event), .current, .params, .onTransition(fn).
Example:
import { useSceneRouter } from '@gwenjs/core/scene'
import { AppRouter } from '../router'
const nav = useSceneRouter(AppRouter)
await nav.send('START') // trigger transition
nav.can('START') // check if valid
nav.current // current state name