gizgame/physics
rigid bodies, their contacts, rays and a character controller, in f64 and in a fixed order, so a server and its clients compute the same steps (gizgame/net predicts with it). A Space holds bodies of four shapes (sphere, capsule along y, box, heightfield) that are static, kinematic or dynamic. A step finds pairs by sweep and prune on x, makes each pair's contacts, and solves them by sequential impulses with warm starting, friction and restitution; a body that stays slow sleeps until a contact or a push wakes it. A fast body is kept from tunnelling by speculative contacts: a pair closer than its approach in one step already pushes back. The state is the bodies' fields alone, so a snapshot is their bytes (bytesOf, restore).
import * as Physics from "gizgame/physics";Types
Field
type Field = { columns: i64; rows: i64; spacing: f64; origin: Point3; heights: Vec<f64>; }A height map over x and z: COLUMNS by ROWS samples SPACING meters apart, its first at ORIGIN (x, z), heights row after row.
columns:i64rows:i64spacing:f64origin:gizlang_geometry.Point3heights:Vec<f64>
Shape
type Shape = { kind: string; radius: f64; half: Point3; field?: Field; }A body's shape: "sphere" (RADIUS), "capsule" (RADIUS, and HALF.y the half length of its core along y), "box" (HALF extents) or "field" (FIELD, static only).
kind:stringradius:f64half:gizlang_geometry.Point3field:_gizlang_sdk_core.Option<M187.Field>
Body
type Body = { id: i64; shape: Shape; motion: i64; mass: f64; friction: f64; restitution: f64; layer: i64; mask: i64; position: Point3; orientation: Rotation; velocity: Point3; spin: Point3; asleep: bool; still: f64; }A body: its shape, motion, mass, surface (FRICTION, RESTITUTION), what it collides with (LAYER is its bit, MASK the bits it meets) and its state; ID is the caller's (an entity's index).
id:i64shape:M187.Shapemotion:i64mass:f64friction:f64restitution:f64layer:i64mask:i64position:gizlang_geometry.Point3orientation:gizlang_geometry.Rotationvelocity:gizlang_geometry.Point3spin:gizlang_geometry.Point3asleep:boolstill:f64
Hit
type Hit = { index: i64; id: i64; distance: f64; point: Point3; normal: Point3; }What a ray hits: the body's index in the space, its ID, the distance and the normal there.
index:i64id:i64distance:f64point:gizlang_geometry.Point3normal:gizlang_geometry.Point3
Space
class Space { bodies: Vec<Body> = []; gravity: Point3 = { x: 0.0, y: -9.81, z: 0.0 }; iterations: i64 = 8; private kept: Vec<Contact> = []; add(b: Body): i64 { this.bodies.push(b); return this.bodies.length-1; } wake(i: i64): void { this.bodies[i].asleep = false; this.bodies[i].still = 0.0; } step(dt: f64): void { for (const at of range(0, this.bodies.length)) { let b = this.bodies[at]; if (b.motion === DYNAMIC && !b.asleep) { b.velocity = add(b.velocity, scale(this.gravity, dt)); this.bodies[at] = b; } } let contacts = this.contacts(dt); for (const at of range(0, contacts.length)) { for (const old of this.kept) { if (old.a === contacts[at].a && old.b === contacts[at].b && length(sub(old.point, contacts[at].point)) <0.05) { contacts[at].normalImpulse = old.normalImpulse; this.apply(contacts[at], contacts[at].normal, old.normalImpulse); break; } } } for (const pass of range(0, this.iterations)) { for (const at of range(0, contacts.length)) { contacts[at] = this.solve(contacts[at], dt); } } this.kept = contacts; for (const at of range(0, this.bodies.length)) { let b = this.bodies[at]; if (b.motion === STATIC || b.asleep) { continue; } b.position = add(b.position, scale(b.velocity, dt)); if (b.shape.kind !== "sphere") { b.orientation = integrate(b.orientation, b.spin, dt); } if (b.motion === DYNAMIC) { const slow = dot(b.velocity, b.velocity) <0.0025 && dot(b.spin, b.spin) <0.0025; b.still = slow ? b.still+dt: 0.0; if (b.still> 0.5) { b.asleep = true; b.velocity = ZERO; b.spin = ZERO; } } this.bodies[at] = b; } } private inverseMass(i: i64): f64 { const b = this.bodies[i]; return b.motion === DYNAMIC && b.mass> 0.0 ? 1.0/b.mass: 0.0; } private inverseInertia(i: i64, n: Point3): f64 { const b = this.bodies[i]; if (b.motion !== DYNAMIC || b.mass <= 0.0) { return 0.0; } const s = b.shape; if (s.kind === "sphere") { return 1.0/(0.4*b.mass*s.radius*s.radius); } const local = unrotate(b.orientation, n); let ix = 0.0; let iy = 0.0; let iz = 0.0; if (s.kind === "box") { const x = 4.0*s.half.x*s.half.x; const y = 4.0*s.half.y*s.half.y; const z = 4.0*s.half.z*s.half.z; ix = b.mass*(y+z)/12.0; iy = b.mass*(x+z)/12.0; iz = b.mass*(x+y)/12.0; } else { const r = s.radius; const h = 2.0*s.half.y+r; iy = 0.4*b.mass*r*r; ix = b.mass*(3.0*r*r+h*h)/12.0; iz = ix; } return local.x*local.x/ix+local.y*local.y/iy+local.z*local.z/iz; } private velocityAt(i: i64, p: Point3): Point3 { const b = this.bodies[i]; return add(b.velocity, cross(b.spin, sub(p, b.position))); } private apply(c: Contact, n: Point3, impulse: f64): void { for (const side of [c.a, c.b]) { const sign = side === c.a ? -1.0: 1.0; const im = this.inverseMass(side); if (im === 0.0) { continue; } let b = this.bodies[side]; const arm = sub(c.point, b.position); const j = scale(n, impulse*sign); b.velocity = add(b.velocity, scale(j, im)); const torque = cross(arm, j); const axis = unitOf(torque); const ii = this.inverseInertia(side, axis); b.spin = add(b.spin, scale(axis, length(torque)*ii)); if (b.asleep) { b.asleep = false; b.still = 0.0; } this.bodies[side] = b; } } private along(c: Contact, n: Point3): f64 { let k = this.inverseMass(c.a)+this.inverseMass(c.b); for (const side of [c.a, c.b]) { const rn = cross(sub(c.point, this.bodies[side].position), n); const l = length(rn); if (l> 1e-12) { k+ = l*l*this.inverseInertia(side, scale(rn, 1.0/l)); } } return k; } private solve(c: Contact, dt: f64): Contact { let out = c; const n = c.normal; const relative = sub(this.velocityAt(c.b, c.point), this.velocityAt(c.a, c.point)); const approach = dot(relative, n); const k = this.along(c, n); if (k <= 0.0) { return out; } const restitution = Math.max(this.bodies[c.a].restitution, this.bodies[c.b].restitution); const bias = c.depth <0.0 ? -c.depth/dt: -0.2/dt*Math.max(0.0, c.depth-0.005); const bounce = approach <-1.0 ? restitution*approach: 0.0; let impulse = -(approach+bias+bounce)/k; const total = Math.max(0.0, out.normalImpulse+impulse); impulse = total-out.normalImpulse; out.normalImpulse = total; this.apply(out, n, impulse); const after = sub(this.velocityAt(c.b, c.point), this.velocityAt(c.a, c.point)); const slide = sub(after, scale(n, dot(after, n))); const speed = length(slide); if (speed> 1e-9) { const t = scale(slide, 1.0/speed); const kt = this.along(c, t); if (kt> 0.0) { const mu = Math.sqrt(this.bodies[c.a].friction*this.bodies[c.b].friction); const most = mu*out.normalImpulse; const f = Math.max(-most, Math.min(most, out.frictionImpulse-speed/kt)); const df = f-out.frictionImpulse; out.frictionImpulse = f; this.apply(out, t, df); } } return out; } private contacts(dt: f64): Vec<Contact> { let order: Vec<i64> = []; let low: Vec<f64> = []; let high: Vec<f64> = []; for (const at of range(0, this.bodies.length)) { const b = this.bodies[at]; const r = reach(b)+length(b.velocity)*dt; order.push(at); low.push(b.position.x-r); high.push(b.position.x+r); } order.sort((a, b) => low[a] <low[b] || low[a] === low[b] && a <b); let out: Vec<Contact> = []; for (const i of range(0, order.length)) { const a = order[i]; for (const j of range(i+1, order.length)) { const b = order[j]; if (low[b]> high[a]) { break; } const p = this.bodies[a]; const q = this.bodies[b]; if (p.motion !== DYNAMIC && q.motion !== DYNAMIC) { continue; } const resting = (x: Body): bool => x.motion === STATIC || x.asleep; if (resting(p) && resting(q) || (p.layer & q.mask) === 0 || (q.layer & p.mask) === 0) { continue; } const first = Math.minI64(a, b); const second = Math.maxI64(a, b); const margin = length(sub(this.bodies[second].velocity, this.bodies[first].velocity))*dt; for (const c of touching(this.bodies[first], this.bodies[second], margin)) { out.push({ a: first, b: second, point: c.point, normal: c.normal, depth: c.depth, normalImpulse: 0.0, frictionImpulse: 0.0 }); } } } return out; } ray(origin: Point3, direction: Point3, farthest: f64, mask: i64 = -1, ignoring: i64 = -1): Hit | undefined { let best: Hit | undefined = undefined; let nearest = farthest; for (const at of range(0, this.bodies.length)) { const b = this.bodies[at]; if (at === ignoring || (b.layer & mask) === 0) { continue; } const d = rayBody(b, origin, direction, nearest); if (d> = 0.0 && d <nearest) { nearest = d; const p = add(origin, scale(direction, d)); best = { index: at, id: b.id, distance: d, point: p, normal: normalOf(b, p) }; } } return best; } overlapping(center: Point3, radius: f64, mask: i64 = -1): Vec<i64> { let out: Vec<i64> = []; for (const at of range(0, this.bodies.length)) { const b = this.bodies[at]; if ((b.layer & mask) === 0) { continue; } if (touching(body(-1, sphere(radius), center, KINEMATIC), b, 0.0).length> 0) { out.push(at); } } return out; } bytesOf(): bytes { let out = b""; for (const b of this.bodies) { for (const v of [b.position.x, b.position.y, b.position.z, b.orientation.x, b.orientation.y, b.orientation.z, b.orientation.w, b.velocity.x, b.velocity.y, b.velocity.z, b.spin.x, b.spin.y, b.spin.z, b.still]) { writeF64LE(out, v); } writeU64LE(out, b.asleep ? 1u: 0u); } return out; } restore(state: bytes): void throws string { if (state.length !== this.bodies.length*120) { throw "The physics snapshot is of other bodies"; } let at: i64 = 0; const f = (): f64 => { const v = state.readF64LE(at); at+ = 8; return v; }; for (const i of range(0, this.bodies.length)) { let b = this.bodies[i]; b.position = { x: f(), y: f(), z: f() }; b.orientation = { x: f(), y: f(), z: f(), w: f() }; b.velocity = { x: f(), y: f(), z: f() }; b.spin = { x: f(), y: f(), z: f() }; b.still = f(); b.asleep = state.readU64LE(at) === 1u; at+ = 8; this.bodies[i] = b; } this.kept = []; } }Bodies under one gravity, stepped together.
bodies:Vec<M187.Body>gravity:gizlang_geometry.Point3iterations:i64— Solver passes of a step: more is stiffer stacks.kept:Vec<M187.Contact>
Character
type Character = { radius: f64; height: f64; step: f64; slope: f64; position: Point3; velocity: Point3; grounded: bool; ground: Point3; }A character: a capsule that walks, not a body that tumbles. Its move slides along what it meets, steps up ledges of STEP meters, stands on slopes up to SLOPE radians and falls from the rest.
radius:f64height:f64step:f64slope:f64position:gizlang_geometry.Point3velocity:gizlang_geometry.Point3grounded:boolground:gizlang_geometry.Point3
Functions
heightAt
function heightAt(f: Field, x: f64, z: f64): f64The field's height at X, Z (bilinear; the border repeats outside).
Effects: fail.
normalAt
function normalAt(f: Field, x: f64, z: f64): Point3The field's upward normal at X, Z.
Effects: fail.
sphere
function sphere(radius: f64): ShapeA sphere of RADIUS.
Effects: fail, read, write, console, io, alloc.
capsule
function capsule(radius: f64, core: f64): ShapeA capsule of RADIUS whose core along y is CORE long.
box
function box(x: f64, y: f64, z: f64): ShapeA box X by Y by Z meters.
field
function field(f: Field): ShapeThe height field F.
Effects: fail, read, write, console, io, alloc.
body
function body(id: i64, shape: Shape, position: Point3, motion: i64 = DYNAMIC, mass: f64 = 1.0): BodyA dynamic body of SHAPE and MASS at POSITION.
Effects: fail, read, write, console, io, alloc.
touching
function touching(p: Body, q: Body, margin: f64): Vec<Touch>The contacts of P and Q (normals from P to Q) within MARGIN of touching. A box meets a box at the corners of each inside the other; a field meets each of the other's lowest points.
Effects: fail, read, write, console, io, alloc.
character
function character(position: Point3, radius: f64 = 0.35, height: f64 = 1.8): CharacterA character of RADIUS and HEIGHT standing at POSITION: it steps up 0.35 m and stands on slopes up to 50 degrees.
Effects: fail, read, write, console, io, alloc.
moved
function moved(space: Space, c: Character, wanted: Point3, dt: f64): CharacterC moved for DT seconds by the walking velocity WANTED (x, z; y is its jump when it stands) through the static and kinematic bodies of SPACE: gravity, then up to four slides, each along the plane of what it met; a blocked move tries again one step higher. POSITION is the capsule's feet.
Effects: fail, read, write, console, io, alloc.
Methods
Space.add
add(b: Body): i64Adds B; its index in bodies names it from now on.
Effects: fail, read, write, alloc.
Space.wake
wake(i: i64): voidWakes body I, as a push or a teleport must.
Effects: fail, read, write.
Space.step
step(dt: f64): voidAdvances DT seconds.
Effects: fail, read, write, console, io, alloc.
Space.ray
ray(origin: Point3, direction: Point3, farthest: f64, mask: i64 = -1, ignoring: i64 = -1): Hit | undefinedThe nearest body that the ray from ORIGIN along the unit DIRECTION meets within FARTHEST, among the bodies whose layer MASK takes, IGNORING one index (the caster's own).
Effects: fail, read, write, alloc.
Space.overlapping
overlapping(center: Point3, radius: f64, mask: i64 = -1): Vec<i64>The indices of the bodies whose reach overlaps the sphere at CENTER of RADIUS (a blast, a trigger).
Effects: fail, read, write, console, io, alloc.
Space.bytesOf
bytesOf(): bytesThe bodies' state as bytes: a snapshot that restore reads back into a space of the same bodies.
Effects: fail, read, alloc.
Space.restore
restore(state: bytes): void throws stringThe bodies as STATE (bytesOf) has them; it fails on a state of other bodies.
Effects: fail, read, write, alloc.
Constants
STATIC
const STATIC: i64 = 0How a body moves: STATIC never, KINEMATIC as its velocity says (it pushes, nothing pushes it), DYNAMIC by forces and contacts.
KINEMATIC
const KINEMATIC: i64 = 1A body that moves as its velocity says.
DYNAMIC
const DYNAMIC: i64 = 2A body that forces and contacts move.