A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file PhysicsTypes.ts
* @brief Shared data shapes for the physics plugin
*
* Plain-data types consumed by `Physics2DPlugin`, `Physics`, and `PhysicsSystem`.
* Kept dependency-free so all three files can import without cycles.
*/
import type { Entity, Vec2 } from '../types';
import { defineResource } from '../ecs/resource';
// =============================================================================
// Plugin configuration
// =============================================================================
export interface Physics2DPluginConfig {
gravity?: Vec2;
fixedTimestep?: number;
subStepCount?: number;
contactHertz?: number;
contactDampingRatio?: number;
contactSpeed?: number;
collisionLayerMasks?: number[];
/** Let bodies sleep when at rest (default true). */
enableSleep?: boolean;
/** Continuous collision (anti-tunneling) for fast bodies (default true). */
enableContinuous?: boolean;
/** Min impact speed (m/s) that produces a bounce; ≤0 keeps the Box2D default. */
restitutionThreshold?: number;
/** Clamp on body speed (world units/s); ≤0 keeps the Box2D default. */
maxLinearSpeed?: number;
}
/** Fully-populated plugin config after defaults are applied. */
export type ResolvedPhysics2DConfig =
Required<Omit<Physics2DPluginConfig, 'collisionLayerMasks'>>
& Pick<Physics2DPluginConfig, 'collisionLayerMasks'>;
// =============================================================================
// Collision events
// =============================================================================
export interface CollisionEnterEvent {
entityA: Entity;
entityB: Entity;
normalX: number;
normalY: number;
contactX: number;
contactY: number;
}
export interface SensorEvent {
sensorEntity: Entity;
visitorEntity: Entity;
}
/** A high-speed impact (approach speed past the world's hit threshold). */
export interface CollisionHitEvent {
entityA: Entity;
entityB: Entity;
pointX: number;
pointY: number;
normalX: number;
normalY: number;
/** Approach speed (world units/s) — impact strength for gameplay reactions. */
approachSpeed: number;
}
/** What `Physics2DEvents` holds for a frame, whose tier this shape carries.
* @beta */
export interface Physics2DEventsData {
collisionEnters: CollisionEnterEvent[];
collisionExits: Array<{ entityA: Entity; entityB: Entity }>;
collisionHits: CollisionHitEvent[];
sensorEnters: SensorEvent[];
sensorExits: SensorEvent[];
}
/**
* This step's collision and trigger events, as a resource. Drained per fixed
* step, so a system reading it must run inside one — a read from `Update` sees
* whatever the last step left.
*
* @beta
*/
export const Physics2DEvents = defineResource<Physics2DEventsData>({
collisionEnters: [],
collisionExits: [],
collisionHits: [],
sensorEnters: [],
sensorExits: []
}, 'Physics2DEvents');
// =============================================================================
// Query result shapes
// =============================================================================
export interface RaycastHit {
entity: Entity;
point: Vec2;
normal: Vec2;
fraction: number;
}
export type ShapeCastHit = RaycastHit;
/** One step of the native kinematic mover: resolved displacement (pixels), slid
* velocity (pixels/s), and the surface contact classification. */
export interface MoverResult {
dx: number;
dy: number;
velX: number;
velY: number;
isOnFloor: boolean;
isOnWall: boolean;
isOnCeiling: boolean;
floorNormalX: number;
floorNormalY: number;
/** The entity it stands on, or null when airborne. */
floorEntity: Entity | null;
/** The dynamic bodies it pressed against this move, with the normals facing it. Absent when none. */
hits?: { entity: Entity; normalX: number; normalY: number }[];
}
/** What else a {@link MoverResult} move is asked to do. */
export interface MoverOptions {
/** Moved with what it stands on, world pixels per second: no part of its own velocity, so what it reports back excludes it. */
carry?: Vec2;
/** Pass through every one-way surface: a drop. */
dropThrough?: boolean;
/** Pass through dynamic bodies. */
ignoreDynamic?: boolean;
/** Treat a slope too steep to stand on as a wall, not something to walk up. */
blockSteepSlopes?: boolean;
/** It stood on a floor before this move: only then can it step over a ledge. */
wasOnFloor?: boolean;
/** The highest ledge it steps over, world pixels. */
stepHeight?: number;
}
export interface MassData {
mass: number;
inertia: number;
centerOfMass: Vec2;
}
// =============================================================================
// WASM buffer strides
// =============================================================================
export const COLLISION_EVENT_STRIDE = 6;
export const HIT_EVENT_STRIDE = 7; // [entityA, entityB, px, py, nx, ny, approachSpeed]
export const CAST_HIT_STRIDE = 6;
// =============================================================================
// Quaternion <-> angle helpers (2D physics lives in XY, rotation on Z)
// =============================================================================
export function quatToAngleZ(q: { w: number; x: number; y: number; z: number }): number {
return Math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z));
}
export function angleZToQuat(angle: number): { w: number; x: number; y: number; z: number } {
const half = angle * 0.5;
return { w: Math.cos(half), x: 0, y: 0, z: Math.sin(half) };
}