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
// The general 4x4 inverse lives in the math layer beside the projections it
// undoes; re-exported here because this module is where the UI already reaches
// for it.
import { invertMatrix4 } from '../../math/mat4';
import { q } from '../../math/quat';
import type { Vec3 } from '../../types';
export { invertMatrix4 };
export interface ScreenRect {
x: number;
y: number;
w: number;
h: number;
}
export function intersectRects(a: ScreenRect, b: ScreenRect): ScreenRect {
const x = Math.max(a.x, b.x);
const y = Math.max(a.y, b.y);
const r = Math.min(a.x + a.w, b.x + b.w);
const t = Math.min(a.y + a.h, b.y + b.h);
return { x, y, w: Math.max(0, r - x), h: Math.max(0, t - y) };
}
/**
* Unprojects one NDC point, depth included.
*
* The full 4×4 product, unlike the x/y-only shortcut it replaces — under a
* perspective projection the third column is not zero, so a screen point does
* not name a world point at all until a depth is chosen.
*/
function unproject(
ndcX: number, ndcY: number, ndcZ: number, m: Float32Array,
): { x: number; y: number; z: number } {
const x = m[0] * ndcX + m[4] * ndcY + m[8] * ndcZ + m[12];
const y = m[1] * ndcX + m[5] * ndcY + m[9] * ndcZ + m[13];
const z = m[2] * ndcX + m[6] * ndcY + m[10] * ndcZ + m[14];
const w = m[3] * ndcX + m[7] * ndcY + m[11] * ndcZ + m[15];
const inv = w !== 0 ? 1 / w : 0;
return { x: x * inv, y: y * inv, z: z * inv };
}
/**
* The world-space ray a screen point names.
*
* @details Every plane it could land on gives a different answer, so the ray is
* what exists and a position is what a chosen plane yields. `dir` is a
* unit vector; `origin` sits on the near plane.
*/
export interface WorldRay {
origin: Vec3;
dir: Vec3;
}
/**
* A pointer position as {@link Input} reports it — CSS pixels, y growing DOWN
* from the top edge — in the framebuffer pixels every projection here takes:
* device pixels, y growing UP from the bottom edge.
*
* @details The one place the two spaces meet. Passing `input.mouseY` straight to
* a screen-space query mirrors the answer about the viewport's centre,
* which is easy to miss in a symmetric scene.
*/
export function pointerToScreen(
pointerX: number, pointerY: number, dpr: number, surfaceH: number,
): { x: number; y: number } {
return { x: pointerX * dpr, y: surfaceH - pointerY * dpr };
}
export function screenRay(
screenX: number, screenY: number,
inverseVP: Float32Array,
vpX: number, vpY: number, vpW: number, vpH: number,
): WorldRay {
const ndcX = ((screenX - vpX) / vpW) * 2 - 1;
const ndcY = ((screenY - vpY) / vpH) * 2 - 1;
const near = unproject(ndcX, ndcY, -1, inverseVP);
const far = unproject(ndcX, ndcY, 1, inverseVP);
const dx = far.x - near.x;
const dy = far.y - near.y;
const dz = far.z - near.z;
const len = Math.hypot(dx, dy, dz) || 1;
return { origin: near, dir: { x: dx / len, y: dy / len, z: dz / len } };
}
/**
* Where @p ray meets the plane through @p point with normal @p normal, or null
* when the two are parallel — a plane the ray never reaches has no point on it,
* and a number would be a position the caller did not ask about.
*/
export function rayPlaneHit(ray: WorldRay, point: Vec3, normal: Vec3): Vec3 | null {
const denom = ray.dir.x * normal.x + ray.dir.y * normal.y + ray.dir.z * normal.z;
if (Math.abs(denom) <= 1e-9) return null;
const t = ((point.x - ray.origin.x) * normal.x
+ (point.y - ray.origin.y) * normal.y
+ (point.z - ray.origin.z) * normal.z) / denom;
return {
x: ray.origin.x + ray.dir.x * t,
y: ray.origin.y + ray.dir.y * t,
z: ray.origin.z + ray.dir.z * t,
};
}
/** The plane 2D content lives on, and the one a caller with no depth in mind means. */
const Z_NORMAL: Vec3 = { x: 0, y: 0, z: 1 };
/**
* Where a screen point lands on the world plane at @p planeZ.
*
* @details A screen point is a RAY, not a position. Orthographically the ray's
* x/y are constant along its length, which is why taking z = 0 worked
* and why every 2D caller can keep calling this unchanged. Under a
* perspective camera they are not constant, and the same call would
* answer with wherever the near plane happened to be — off by more the
* further the content sits from z = 0.
*
* So the ray is intersected with the plane, which is one implementation
* with the orthographic case as its degenerate form rather than two
* branches that have to agree. `planeZ` defaults to the 2D plane, so a
* caller that has no depth in mind keeps getting the 2D answer.
*/
export function screenToWorld(
screenX: number, screenY: number,
inverseVP: Float32Array,
vpX: number, vpY: number, vpW: number, vpH: number,
planeZ = 0,
): { x: number; y: number } {
const ray = screenRay(screenX, screenY, inverseVP, vpX, vpY, vpW, vpH);
// A ray parallel to the plane it is being intersected with has no answer;
// the near point is the closest thing to one, and it is what the
// orthographic path returned before this existed.
const hit = rayPlaneHit(ray, { x: 0, y: 0, z: planeZ }, Z_NORMAL);
return hit ? { x: hit.x, y: hit.y } : { x: ray.origin.x, y: ray.origin.y };
}
export function pointInWorldRect(
px: number, py: number,
worldX: number, worldY: number,
worldW: number, worldH: number,
pivotX: number, pivotY: number
): boolean {
const left = worldX - worldW * pivotX;
const right = worldX + worldW * (1 - pivotX);
const bottom = worldY - worldH * pivotY;
const top = worldY + worldH * (1 - pivotY);
return px >= left && px <= right && py >= bottom && py <= top;
}
export function quaternionToAngle2D(rz: number, rw: number): number {
return q.angleZ({ z: rz, w: rw });
}
/**
* A world point in clip space, and where that lands on screen.
*
* @details @p x / @p y are a position only while @p clipW is positive: behind the eye
* the divide flips both signs, mirroring the point into a screen position
* nothing tells from a real one. @p clipZ cuts a segment at the near plane.
*/
export interface ProjectedPoint {
x: number;
y: number;
clipZ: number;
clipW: number;
}
/** At or below this, w names the eye itself and the divide has no answer. */
export const CLIP_W_EPSILON = 1e-6;
/** Whether the point has a screen position at all — see {@link ProjectedPoint}. */
export function isProjectable(p: ProjectedPoint): boolean {
return p.clipW > CLIP_W_EPSILON;
}
/**
* Where a world point lands on screen — the inverse of {@link screenToWorld}, and
* it takes the same third dimension.
*
* @details A point off the z = 0 plane projects to a different place than its
* shadow on it: nearer content is larger and further from the centre.
* Dropping @p wz would put an entity's outline, gizmo and screen rect
* where the entity is NOT drawn. No default: which plane a point sits on
* is the caller's fact, not this function's guess.
*/
export function projectWorldPoint(
wx: number, wy: number, wz: number,
vp: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number,
): ProjectedPoint {
const clipX = vp[0] * wx + vp[4] * wy + vp[8] * wz + vp[12];
const clipY = vp[1] * wx + vp[5] * wy + vp[9] * wz + vp[13];
const clipZ = vp[2] * wx + vp[6] * wy + vp[10] * wz + vp[14];
const clipW = vp[3] * wx + vp[7] * wy + vp[11] * wz + vp[15];
const ndcX = clipX / clipW;
const ndcY = clipY / clipW;
return {
x: vpX + (ndcX * 0.5 + 0.5) * vpW,
y: vpY + (ndcY * 0.5 + 0.5) * vpH,
clipZ,
clipW,
};
}
/**
* How far a projected point is in FRONT of the near plane, in clip units.
*
* @details Negative behind it, and affine along a world segment — so where a
* segment crosses solves for one t, and the world point at that t is the
* furthest the segment can be drawn to.
*/
export function nearPlaneSide(p: ProjectedPoint): number {
return p.clipZ + p.clipW;
}
/**
* How a world direction moves the projection of its own anchor, in viewport
* pixels per world unit, y-up.
*
* @details Under perspective the answer depends on the POINT: the divide by w
* swings an axis's screen direction with where it stands.
*/
export function projectDirectionAt(
at: ProjectedPoint,
dx: number, dy: number, dz: number,
vp: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number,
): { x: number; y: number } {
const ndcX = ((at.x - vpX) / vpW) * 2 - 1;
const ndcY = ((at.y - vpY) / vpH) * 2 - 1;
const cx = vp[0] * dx + vp[4] * dy + vp[8] * dz;
const cy = vp[1] * dx + vp[5] * dy + vp[9] * dz;
const cw = vp[3] * dx + vp[7] * dy + vp[11] * dz;
return {
x: ((cx - ndcX * cw) / at.clipW) * 0.5 * vpW,
y: ((cy - ndcY * cw) / at.clipW) * 0.5 * vpH,
};
}
export function createInvVPCache() {
const invVP = new Float32Array(16);
const cachedVP = new Float32Array(16);
let dirty = true;
return {
update(vp: Float32Array): void {
for (let i = 0; i < 16; i++) {
if (cachedVP[i] !== vp[i]) {
cachedVP.set(vp);
dirty = true;
break;
}
}
},
getInverse(vp: Float32Array): Float32Array {
if (dirty) {
invertMatrix4(vp, invVP);
dirty = false;
}
return invVP;
},
};
}
export function pointInOBB(
px: number, py: number,
worldX: number, worldY: number,
worldW: number, worldH: number,
pivotX: number, pivotY: number,
rotationZ: number, rotationW: number,
): boolean {
if (rotationZ === 0 && rotationW === 1) {
return pointInWorldRect(px, py, worldX, worldY, worldW, worldH, pivotX, pivotY);
}
const angle = quaternionToAngle2D(rotationZ, rotationW);
const sin = Math.sin(-angle);
const cos = Math.cos(-angle);
const dx = px - worldX;
const dy = py - worldY;
const localX = dx * cos - dy * sin + worldX;
const localY = dx * sin + dy * cos + worldY;
const left = worldX - worldW * pivotX;
const right = worldX + worldW * (1 - pivotX);
const bottom = worldY - worldH * pivotY;
const top = worldY + worldH * (1 - pivotY);
return localX >= left && localX <= right && localY >= bottom && localY <= top;
}