commit 11d94dba85f28abe8571cefaddc9242164caa620 Author: SoraKatadzuma Date: Tue Oct 27 22:08:25 2026 -0500 Initial Commit diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c6c8b36 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cfecb95 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.blossom diff --git a/README.md b/README.md new file mode 100644 index 0000000..a346179 --- /dev/null +++ b/README.md @@ -0,0 +1,326 @@ +# physics +The numbers of physical space and what's in it, as games, their renderers, and their physics work them, in five libraries: + +| Library | What it is | +|---|---| +| `malunal.linear` | Vectors of two, three, and four `f32`s, rotations as quaternions, and matrices of three by three and four by four | +| `malunal.geometry` | The shapes of space made of them, rays, planes, boxes, spheres, and a camera's frustum, and the tests between them | +| `malunal.photometry` | Light in the units it's measured in, lumens, candela, lux, and nits, converted between them; exposure values; and the colors of temperatures | +| `malunal.physics2d` | What collides and moves in a plane: circles, capsules, and convex polygons, where and how deep two meet, how far apart they are, shapes cast and swept, rays, a tree of boxes, a grid of solid cells, as a tilemap's walls are, and chains of segments; and a space of rigid bodies, pushed by forces and what they meet, kept from passing through what's thin, held by joints, sleeping at rest, and solved on several threads; what it's asked of the shapes in it; and characters walked through it | +| `malunal.physics3d` | What collides and moves in space: spheres, capsules, and convex hulls, boxes among them, where and how deep two meet, how far apart they are, shapes cast and swept, rays, a tree of boxes, the triangles of a surface, as a level's ground and walls are, and heightfields; and a space of rigid bodies, as in a plane | + +It's Sakura's, built with [blossom](https://git.malunal.studio/sakura/blossom), and reads only std's `containers`, `math`, `serial`, `thread`, which solves a space's steps on several threads, and `time`, which times them. An executable optimized with `-O2` works what `linear` and `geometry` do to whole vectors as SIMD lanes, which the virtual machine works a number at a time, giving the same bits. It was the package `linear`, of `linear` and `geometry`, until `photometry`, `physics2d`, and `physics3d` joined them. + +```sakura +import std::math; +import malunal::linear; + +val up := vec3::up; +var at := vec3{ 1, 2, 3 }; +at = at + vec3{ x = 0.5 } * 2; # vec3{ 2, 2, 3 } +val ahead := at.cross(up).normalized(); +val far := at.dot(ahead) + at.length; + +val turn := quat::axis_angle(vec3::back, math::pi as f32 / 2); +val turned := turn * vec3::right; # vec3::up, as near as f32 gets +val both := quat::euler(0.3, -1.1, 0.7) * turn; # turn, then the other + +val place := mat4::compose(vec3{ 5, 0, -2 }, turn, vec3::one); +val moved := place.transform_point(vec3::zero); # vec3{ 5, 0, -2 } +val clip := mat4::perspective(math::pi as f32 / 3, 16.0 / 9.0, 0.1, 100) * mat4::look_at(vec3{ 0, 2, 10 }, vec3::zero); + +val inertia := mat3::rotation(turn) * mat3::scaling(vec3{ 2, 1, 1 }) * mat3::rotation(turn).transposed(); +``` + +```sakura +import malunal::linear; +import malunal::geometry; + +val seen := frustum::of(clip); # the camera's six planes, facing in +val crate := bounds::around(vec3{ 4, 1, -6 }, vec3::one); +val drawn := seen.overlaps(crate); # true: it's in view +val under := ray::toward(vec3{ 0, 2, 10 }, crate.center); +val reach := under.hit(crate) is some(t) ? t : -1; # how far along it meets the box +val ground := plane::through(vec3::zero, vec3::up); +val lying := ground.side_of(sphere{ vec3{ 0, 0.5, 0 }, 1 }); # side::across +val carried := crate.transformed(place); # the box holding the crate moved +``` +```sakura +import malunal::linear; +import malunal::photometry; + +val bulb := candela_of_lumens(lumens::bulb_60w); # about 63.7 candela, every way +val torch := candela_of_lumens(300, 0.2); # 300 lumens gathered into a cone of 0.2 radians each way +val lit := lux_of_candela(bulb, 2); # what it lights a surface 2 meters away with +val metered := ev100_of_lux(lux::office); # about 7.3, as a meter where it's lit reads +val scale := exposure_of_ev100(metered); # what light in nits is multiplied by, so exposed +val warm := color_of_temperature(2700); # a warm bulb's color, linear sRGB +``` + +```sakura +import malunal::linear; +import malunal::physics2d; + +val crate := shape::box(vec2{ 0.5, 0.5 }); +val ball := shape::circle(0.25); +val met := collide(&crate, pose::of(vec2{ 0, 0 }), &ball, pose::of(vec2{ 0.6, 0.1 })); # the manifold: normal, points, depths +val ray := crate.ray_cast(pose::of(vec2{ 3, 0 }, 0.3), vec2::zero, vec2{ 1, 0 }, 10); # where a ray first meets the turned crate + +var tree := aabb_tree::new(); +val leaf := tree.insert(crate.bounds(pose::identity), 7); # a box and a number of the user's +tree.query(aabb::around(vec2::zero, vec2{ 2, 2 }), def(leaf: u32, data: u64): bool { ...; return true; }); + +var walls := grid::new(20, 10); # solid cells, as a tilemap's walls +walls.set(3, 0, true); +walls.collide(pose::identity, &ball, pose::of(vec2{ 3.5, 1.2 }), def(x: u32, y: u32, m: manifold): bool { ...; return true; }); +``` + +```sakura +import malunal::linear; +import malunal::physics3d; + +val crate := shape::box(vec3{ 0.5, 0.5, 0.5 }); +val rock := shape::hull_of(places.span).expect("..."); # the convex hull of places, as many as 32 its corners +val met := collide(&crate, pose::identity, &rock, pose::of(vec3{ 0.2, 0.9, 0 }, turn)); # the manifold: normal, one to four points, depths +val hit := crate.ray_cast(pose::of(vec3{ 3, 0, 0 }), vec3::zero, vec3{ 1, 0, 0 }, 10); # where a ray first meets the crate + +val ground := triangle_mesh::new(points.span, indices.span); # a level's triangles, in a tree of their own +ground.collide(pose::identity, &crate, pose::of(vec3{ 0, 0.45, 0 }), 0, def(t: u32, m: manifold): bool { ...; return true; }); +``` + +```sakura +import malunal::linear; +import malunal::physics2d; + +var s := space::new(); # gravity 10 down, lengths in meters +val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, -1 }) }); +_ = s.attach(ground, collider{ shape = shape::box(vec2{ 50, 1 }) }); +val crate := s.add(body{ at = pose::of(vec2{ 0, 4 }) }); # dynamic, as bodies are at first +_ = s.attach(crate, collider{ shape = shape::box(vec2{ 0.5, 0.5 }), density = 2, friction = 0.8 }); +val door := s.add(body{ at = pose::of(vec2{ 6, 2 }) }); +_ = s.attach(door, collider{ shape = shape::box(vec2{ 1, 0.1 }) }); +val hinge := s.pin(ground, door, vec2{ 5, 2 }); # a revolute joint, limits and a motor its own to set +val piston := s.slide(ground, crate, vec2{ 0, 4 }, vec2{ 1, 0 }); # prismatic, wheel, motor, and mouse joints too +_ = s.attach_chain(ground, hills.span, false, collider{}); # ground of a chain of segments, met from above +_ = s.attach(ground, collider{ shape = shape::box(vec2{ 2, 0.1 }, vec2{ 0, 3 }), one_way = true }); # a platform jumped through from below +s.apply_impulse(crate, vec2{ 2, 0 }, s.center_of(crate)); +for i in 0..60u { + s.step(1f / 60f); # four substeps, as Box2D's soft step +} +val at := s.pose_of(crate); # resting on the ground, near y = 0.5 +for e in s.events() { ... } # what began and stopped touching +val hit := s.ray_cast(vec2{ 0, 10 }, vec2{ 0, -1 }, 20); # the collider, its body, and where +``` + +```sakura +import malunal::linear; +import malunal::physics3d; + +var s := space::new(); +val level := s.add(body{ kind = body_kind::static }); +_ = s.attach_mesh(level, triangle_mesh::new(points.span, indices.span), collider{ friction = 0.8 }); # a level's triangles +val ball := s.add(body{ at = pose::of(vec3{ 0, 5, 0 }), velocity = vec3{ 2, 0, 0 } }); +_ = s.attach(ball, collider{ shape = shape::sphere(0.5), restitution = 0.5 }); +val wheel := s.add(body{ at = pose::of(vec3{ 4, 2, 0 }) }); +_ = s.attach(wheel, collider{ shape = shape::capsule(vec3{ 0, 0, -0.2 }, vec3{ 0, 0, 0.2 }, 0.5) }); +val axle := s.hinge(level, wheel, vec3{ 4, 2, 0 }, vec3::back); # ball, hinge, fixed, distance, slider, and six-way joints +val shoulder := s.cone_twist(level, arm, vec3{ 0, 2, 0 }, vec3::right, 0.8, 0.4); # a ball joint swinging within a cone, twisting so far +s.threads = 8; # each step solved on eight threads, giving the same +s.step(1f / 60f); +``` + +```sakura +import malunal::linear; +import malunal::physics3d; + +val hit := s.shape_cast(&shape::sphere(0.5), pose::of(vec3{ 0, 5, 0 }), vec3{ 0, -10, 0 }); # where a ball dropped first meets what's below +s.overlap(&shape::box(vec3{ 1, 1, 1 }), pose::identity, 0xFFFFFFFF, def(c: collider_id, b: body_id): bool { ...; return true; }); +val apart := gap_between(&a, at_a, &b, at_b); # how far apart two shapes are, and their nearest places +val terrain := heightfield::new(129, 129, heights.span, vec2{ 2, 2 }); # a terrain's heights, two meters apart +_ = s.attach_heightfield(level, move(terrain), collider{}); +var walker := character{ at = vec3{ 0, 1, 0 } }; # a capsule a game walks +s.move_character(&mut walker, vec3{ 2, -1, 0 }, 1f / 60f); # sliding, stepping up, and kept to the ground +val ok := walker.grounded; +walker.up = walker.at.normalized(); # on a world at the middle, standing away from it +s.set_gravity(rock, s.center_of(rock).normalized() * -9.81); # a body's own pull, toward the world's middle +for h in s.hits() { ... } # what began touching fast, and how fast +``` +`tests/linear.sakura`, `tests/geometry.sakura`, `tests/photometry.sakura`, `tests/physics2d.sakura`, `tests/space2d.sakura`, `tests/physics3d.sakura`, and `tests/space3d.sakura` drive all of it; `tools/bench.sakura` and `tools/geometry_bench.sakura` time `linear` and `geometry`, and `tools/physics2d_bench.sakura` and `tools/physics3d_bench.sakura` step Box2D's and Jolt's benchmark scenes. + +A project reads it by requiring this folder, or its remote, and naming the libraries it uses among a target's `deps`, as `malunal.geometry`, whose module is `malunal::geometry`; each brings `malunal.linear`, which they read: + +```yaml +requires: +- https://git.malunal.studio/malunal/physics@v1.0.0 +targets: +- name: game + type: program + deps: [malunal.geometry, malunal.photometry, malunal.physics2d, malunal.physics3d] +``` + +## Layout +| Path | Holds | +|---|---| +| `linear/linear.sakura` | The conventions, and reading a value of four `f32`s as one `f32x4` where it lies | +| `linear/vec2.sakura` | `vec2`: a place or direction in a plane | +| `linear/vec3.sakura` | `vec3`: a place or direction in space, and the axes' directions | +| `linear/vec4.sakura` | `vec4`: a place of space with its `w`, as a matrix projects one | +| `linear/quat.sakura` | `quat`: rotations by an axis and angle, by angles about each axis, by where they look, between two directions, and of a basis; turning vectors, following, undoing, and `slerp` | +| `linear/mat3.sakura` | `mat3`: rotations, scales, and what turns directions, as an inertia tensor; transposes, determinants, and inverses | +| `linear/mat4.sakura` | `mat4`: moving, turning, scaling, and composing them; perspective and orthographic projections; `look_at`; points and directions moved; inverses | +| `geometry/geometry.sakura` | The conventions of `geometry`, and the dot products and lanes its shapes are worked with | +| `geometry/ray.sakura` | `ray`: a half line from a place, its places, and where it first meets a plane, a sphere, or a box | +| `geometry/plane.sakura` | `plane`: through a place or three, how far a place is in front, and which `side` of it a box or sphere lies on | +| `geometry/bounds.sakura` | `bounds`: a box along the axes, of places or a sphere; what it holds and meets; grown, merged, and moved by a matrix | +| `geometry/sphere.sakura` | `sphere`: what it holds and meets, and the least one holding a box | +| `geometry/frustum.sakura` | `frustum`: the six planes of what a projection sees, and whether a place, a box, or a sphere is within them | +| `photometry/photometry.sakura` | The units, and lumens, candela, lux, and nits converted between them, of lights every way and within cones; lumens of watts; and what's commonly lit, as `lux::office`, `nits::clear_sky`, and `lumens::bulb_60w` | +| `photometry/exposure.sakura` | Exposure values at ISO 100, of a camera's settings or what its meter reads, and what light is multiplied by, so exposed | +| `photometry/temperature.sakura` | The color of a black body's light at a temperature, as lamps' colors are named | +| `physics2d/physics2d.sakura` | The conventions of `physics2d`, and the nearest points of segments | +| `physics2d/pose.sakura` | `rot`, a rotation in the plane, and `pose`, where a body is and which way it's turned | +| `physics2d/aabb.sakura` | `aabb`, a box along the plane's axes: what it holds and meets, grown, merged, and where a ray meets it | +| `physics2d/shape.sakura` | `shape`: circles, capsules, segments, boxes, and convex polygons, as the hull of places; the box holding one, what it holds, and where a ray first meets it | +| `physics2d/collide.sakura` | `collide` and `overlaps`: the `manifold` of where two shapes meet, its normal and one or two points, each with its depth | +| `physics2d/tree.sakura` | `aabb_tree`: boxes kept in a tree of boxes, inserted, moved, and removed, and found by a box or along a ray | +| `physics2d/grid.sakura` | `grid`: solid cells, the manifolds of a shape against them, but for the faces they share, and rays passed from cell to cell | +| `physics2d/mass.sakura` | `mass_data`: a shape's mass of a density, its center, and its rotational inertia, and two summed | +| `physics2d/body.sakura` | `body_kind`, `body`, and `collider`, what a space makes bodies and colliders of, and the ids naming them | +| `physics2d/space.sakura` | `space`: bodies and colliders added, attached, and taken away, a grid among them; their poses, velocities, and masses; forces, torques, and impulses; rays; and the step, timed by its `step_profile` | +| `physics2d/contacts.sakura` | Pairs of colliders found by the tree as they move, their contacts kept from step to step, a grid's one for each cell, and `contact_event`s of what began and stopped touching | +| `physics2d/solver.sakura` | The soft step: substeps of forces, pushes, moves, and relaxing, bouncing, and each contact's impulses kept | +| `physics2d/wide.sakura` | Contacts sorted into colors, none of whose bodies any other of its color pushes, and solved as lanes of eight | +| `physics2d/sleep.sakura` | Islands of bodies touching or joined, put to sleep together, and woken | +| `physics2d/joints.sakura` | `joint`: revolute, distance, and weld joints, made and changed, and how they keep bodies from meeting | +| `physics2d/joint_solver.sakura` | How each kind of joint is prepared, warmed, and solved, its limits, motor, and spring among it | +| `physics2d/drive_joints.sakura` | How prismatic, wheel, motor, and mouse joints are solved | +| `physics2d/distance.sakura` | `gap_between`, how far apart two shapes are, by GJK; `shape_cast`; `sweep`, how a body moves through a step; and `time_of_impact` | +| `physics2d/continuous.sakura` | Fast bodies swept through a step against what stands still, bullets against what moves too, and put back where they first meet it | +| `physics2d/chains.sakura` | `space::attach_chain`, chains of segments met from one side and passed over at their joints, and one-way colliders | +| `physics2d/queries.sakura` | `space::overlap` and `space::shape_cast`: which colliders a shape overlaps, and where a shape cast first meets one | +| `physics2d/character.sakura` | `character`, a body a game walks, and `space::move_character` | +| `physics2d/crew.sakura` | The threads a step's colors are solved on | +| `physics3d/physics3d.sakura` | The conventions of `physics3d`, and the nearest points of segments | +| `physics3d/pose.sakura` | `pose`, where a body is in space and which way it's turned, as a place and a quaternion | +| `physics3d/hull.sakura` | `hull`: a convex polyhedron's corners, faces, and edges; made as a box, as a triangle, or around places, coplanar triangles made one face | +| `physics3d/shape.sakura` | `shape`: spheres, capsules, boxes, and convex hulls; the box holding one, what it holds, and where a ray first meets it | +| `physics3d/collide.sakura` | `collide` and `overlaps`: the `manifold` of where two shapes meet, its normal and one to four points, each with its depth and the features that met | +| `physics3d/tree.sakura` | `aabb_tree`: boxes kept in a tree of boxes, inserted, moved, and removed, and found by a box or along a ray | +| `physics3d/mesh.sakura` | `triangle_mesh`: the triangles of a surface, in a tree, their shared edges flat or hollow passed over, met by shapes and rays | +| `physics3d/mass.sakura` | `mass_data`: a shape's mass of a density, its center, and its inertia tensor, and two summed | +| `physics3d/body.sakura` | `body_kind`, `body`, and `collider`, what a space makes bodies and colliders of, and the ids naming them | +| `physics3d/space.sakura` | `space`: bodies and colliders added, attached, and taken away, a triangle mesh among them; their poses, velocities, and masses; forces, torques, and impulses | +| `physics3d/step.sakura` | The step, timed by its `step_profile`, and rays | +| `physics3d/contacts.sakura` | Pairs of colliders found by the tree as they move, their contacts kept from step to step, a mesh's one for each face of triangles met, and `contact_event`s | +| `physics3d/solver.sakura` | The soft step, as in a plane, each contact of as many as four points, its friction along two tangents | +| `physics3d/sleep.sakura` | Islands of bodies touching or joined, put to sleep together, and woken | +| `physics3d/joints.sakura` | `joint`: ball, hinge, fixed, and distance joints, made and changed, and how they keep bodies from meeting | +| `physics3d/joint_solver.sakura` | How each kind of joint is prepared, warmed, and solved, a hinge's limits, motor, and spring among it | +| `physics3d/free_joints.sakura` | How sliders, ball joints' cones and twists, and six-way joints are solved, a joint's turn taken as a swing after a twist | +| `physics3d/wide.sakura` | Contacts sorted into colors and solved as lanes of eight, as a plane's are | +| `physics3d/distance.sakura` | `gap_between`, by GJK in space; `shape_cast`; `sweep`; and `time_of_impact` | +| `physics3d/continuous.sakura` | Fast bodies swept against what stands still, a mesh's triangles and a heightfield's among it, and bullets against what moves | +| `physics3d/queries.sakura` | `space::overlap` and `space::shape_cast` | +| `physics3d/heightfield.sakura` | `heightfield`: a terrain's heights on a grid, its triangles made as they're met, and rays passed from square to square | +| `physics3d/character.sakura` | `character`, a body a game walks, and `space::move_character` | +| `physics3d/crew.sakura` | The threads a step's colors are solved on | + +## How it works +- **Space** is right-handed: x to the right, y up, z toward the viewer, so a camera looks down its -z. Matrices are column-major, as GLSL reads them, and multiply a vector on their right, so `a * b` does `b`, then `a`, as quaternions' products do. Projections give a clip space of y up and depth from 0 at the near plane to 1 at the far one, as Vulkan's with its y flipped. Angles are radians. +- **Plain fields**: each type is of `f32` fields, aligned as an `f32`, so a struct holding one lays it out wherever it falls, as C and the GPU do, and the virtual machine reads a field as quickly as any. `vec3` holds a fourth `f32` no one names, so it's 16 bytes, an `f32x4`'s, as `vec4` and `quat` are. It's 0 as a literal leaves it, as `vec3{ 1, 2, 3 }` and `vec3{ y = 1 }` do, and printing a `vec3` shows it as `_w`. A `mat3`'s columns are `vec3`s, so it's laid out as std140 lays out a GLSL `mat3`; a `mat4` is its 16 numbers, column after column. +- **Lanes**: an executable optimized with `-O2` holds `simd` vectors in registers, so it reads a `vec3`, `vec4`, or `quat` as one `f32x4` from where it is, aligned or not, and works lanes at once: adding, subtracting, scaling, and dividing vectors, their least, greatest, and absolute numbers, `lerp`, dots, lengths, `distance`, and `normalized`, and what a matrix makes of a vector or another matrix, each of its columns scaled by a number splat into every lane, and added, as a `quat` turns a vector by its matrix. What gathers one vector's numbers into other lanes, as a cross product or a quaternions' product would, it works a number at a time, as `simd::shuffle` gathers them a lane at a time. `lanes_held()` says which way while compiling, so only that way's code is kept. `lanes()` and `of_lanes` give a `vec3`'s, `vec4`'s, or `quat`'s numbers as an `f32x4`, for code of one's own to work. +- **The same bits**: the virtual machine, which works lanes one at a time, and constants work everything a number at a time, in the order the lanes do, so either way gives the same bits; `tests/linear.sakura` folds the bits of a long chain of operations, and the machine and an executable each check they're those. +- **Shapes**: `geometry`'s shapes are of `linear`'s vectors and plain `f32`s. A `frustum` is of a matrix's clip space as `linear`'s projections make it, so `frustum::of(projection * view)` gives the world's planes, and `frustum::of(projection)` the camera's; it holds its planes' numbers a lane each, so an executable tests a place, a box, or a sphere against four planes at once, then the other two. A box against a frustum is tested by its corner furthest in front of each plane, so one beside a corner of the frustum, outside it but in front of every plane, counts as seen, which draws it for nothing, and one in view always counts. A place on a shape's surface is within it, and two shapes touching meet. A ray's distances are counted in lengths of its direction, so they're distances where it's of length 1, as `ray::toward` makes it, and a ray beginning within a sphere or box meets it at 0. What gives a number of a few, as a dot product does, is worked a number at a time: of the lanes of `vec3::dot`, then worked as numbers, a ray's tests ran two to three times as slow. A ray's test against a box compares its numbers rather than calling `math::min` and `math::max`, which keep NaN and `-0` as IEEE 754 orders them at three times the cost, so a ray running along a face, in its plane, may meet the box or pass by. +- **Written and read**: each type but `frustum` is `@serial`, so `std::serial`, and any format of it, as `std::yaml` and `std::json`, writes and reads it: a vector or rotation as a mapping of its numbers, as `{x: 1, y: 0.1, z: -2.5}`, each the shortest text reading back as the same `f32`, with `vec3`'s fourth number left out; a `mat3` as its axes; a `mat4` as a sequence of its 16 numbers, column after column; and `geometry`'s shapes by their fields. Read with `serial::options{ defaults = true }`, a number left out is 0, and a rotation's `w` 1. A `frustum` holds its planes as lanes, and is made again of its matrix. +- **Light's units**: `photometry` gives each of light's quantities in its own unit, as real lights are measured: a source's luminous flux in lumens, all the light it gives, as a bulb is sold by; its luminous intensity in candela, the light it gives one way, in each steradian; the illuminance of a surface in lux, the light falling on it; and a surface's or a sky's luminance in nits, candela a square meter, the light it gives back toward an eye. A light every way spreads its lumens over 4π steradians, and one within a cone over the cone's solid angle, 2π(1 - cos angle), of its angle from its axis to its edge, as glTF gives a spot light's; a surface so far from a light of so many candela is lit by candela over the distance squared; and a matte surface gives back what lights it over π, by the fraction it gives back. An exposure value at ISO 100 is of a camera's aperture, shutter, and ISO, or of what a meter reads, calibrated as reflected-light meters are, by 12.5, and incident-light meters, by 250, so a scene exposed as a meter where it's lit reads gives a white surface about two thirds of the most a camera records, 1.2 × 2^EV100 nits, and middle grey about an eighth. A temperature's color is of Krystek's fit of the Planckian locus, made linear sRGB of CIE 1931's XYZ. What's commonly lit and sold is named as constants of empty types, so `lux::office` and `lumens::bulb_60w` read as what they are. +- **Collision in a plane**: `physics2d` takes each shape as a hull, its points where its pose places them, and its radius around them: a circle of one point, a capsule of two, of no radius a segment, and a polygon of three to eight corners, counterclockwise, each edge's normal facing out. Two circles meet as their middles near; a circle and a hull as the circle's middle nears the hull's edges, or lies within it; and two hulls by the edge of either holding them furthest apart, as the separating axis theorem finds it. Where their hulls overlap, or their round sides near along a face, the other's nearest edge is clipped to the face, as Box2D clips one, so a box resting flat on another, or a capsule lying on one, meets it at two points; where only their round sides meet, at one, along the line between the hulls' nearest points. A manifold's normal is from the first shape toward the second, and each point midway between their surfaces, with how deep the one is within the other; two shapes touching meet, at a depth of 0. A ray meets a circle by its quadratic, a polygon as Cyrus and Beck clip a line by each edge's side, and a capsule by its flat sides between its ends, else its round ends; one beginning within a shape meets it at 0, facing back along it. +- **The tree**: an `aabb_tree` keeps a box and a number of the user's at each leaf, each branch the least box holding its two children, so a query passes down only the branches that reach what it asks, and a ray's narrows as it meets what's nearer. A leaf's box is grown by the tree's margin, so what moves a little stays within it and the tree isn't changed; a leaf is put where it grows the boxes above it least, and each branch it passes is turned, as an AVL tree turns one, where one child is two or more deeper than the other: 500 boxes in any order make a tree 18 deep at most. +- **Grids**: a `grid` holds solid cells, from its origin at the bottom left of its first, each a box of its cell size. A shape meets each solid cell it reaches as a box, but a manifold pushing it into a solid neighbor, along the axis it pushes most, is passed over, as that's a face two cells share: so a body sliding along a floor of many cells slides as along one, never caught on the seams between them, the ghost collisions of tile maps. A ray passes from cell to cell as Amanatides and Woo pass one, entering by a face, which is its normal. +- **Collision in space**: `physics3d` takes each shape as a core with its radius around it: a sphere's a place, a capsule's a segment, and a hull itself, of no radius. A hull is plain data, as many as 32 corners, its faces convex polygons, counterclockwise from outside, and each edge between two faces; `hull::of` makes the least one around places by adding them one at a time, the furthest first, each replacing the faces it sees with faces from their horizon to it, then makes the triangles of one plane one face, so a box of eight places is six squares. Two spheres or capsules meet as their cores near, a capsule lying along another at two points. A sphere or capsule and a hull meet as the core nears the hull's surface, by its places nearest a face it's in front of and its edges', a capsule lying along a face at two; or, where the core passes within the hull, by the face, or the axis across an edge and the segment, holding them furthest apart. Two hulls meet by the face of either, or the pair of edges, one of each, holding them furthest apart, as the separating axis theorem finds it, testing only the pairs of edges whose arcs on the sphere of directions cross, as Gregorius tests them, so they're a face of the hulls' Minkowski difference; a flat hull's edges, a triangle's, are tested by how far the hulls reach along each axis. At a face, the other's face most against it is clipped to its sides, as Sutherland and Hodgman clip, at as many as four points, those holding most of what the rest hold; at two edges, at one, between them. A face of the second hull is taken over the first's only where it holds them apart by a millimeter and 2 percent more, and an edge over a face by a millimeter and 5 percent, so the same pair meets the same way from one step to the next, as deep as it is to within those. Each point has an id of the features that met there, for a solver to carry over what it found; within a `margin`, shapes apart are given points too, of depths below 0. A ray meets a sphere by its quadratic, a capsule's side as Ericson meets a cylinder, and its ends as spheres, and a hull as Cyrus and Beck clip a line by each face's side. +- **Meshes**: a `triangle_mesh` keeps its triangles, those of no area left out, in a tree of their boxes, and a shape meets each triangle it reaches as a flat hull. An edge two triangles share is passed over where they're flat, turning less than 5 degrees, or hollow, as Jolt's active edges are: a shape meeting a triangle by such an edge, or a corner of such edges only, is pushed out as the triangle's face pushes it, as deep as it is below the face's plane, so a body sliding across a floor of many triangles slides as along one. A ray meets each triangle from either side, as Möller and Trumbore find it, its normal facing back along the ray. +- **Bodies**: a `space` holds bodies, each static, standing where it's put; kinematic, moving by the velocity it's given and pushing what it meets but never pushed; or dynamic, moving by forces, gravity, and what it meets. A body is made of colliders, each a shape about the body's origin, or a `grid` or a `triangle_mesh`, which a static body is given as a level's walls are, and its mass is its colliders' areas or volumes by their densities, centered where they're centered, and its rotational inertia about that center, as the parallel axis theorem sums them. Gravity pulls each dynamic body by its `gravity_scale`: the space's, and a `gravity` of the body's own added to it, which `set_gravity` changes as it goes, as a world's pull toward its middle turns as a body goes around it, waking the body only where that turns or grows the pull by more than a hundredth. A body's data and a collider's are a number of the user's, as an entity's bits. Ids name bodies, colliders, and joints by their place and a generation, so one kept past its removal is never taken for the next of its place. +- **Pairs and contacts**: each collider is a leaf of the space's tree, its box grown by a tenth of a meter, and each that leaves its grown box as its body moves finds what its box newly meets: a pair, where the two may meet, of bodies one of them dynamic, or of a sensor and a body that isn't static, as a coin notes a kinematic character walking into it, on layers each other's masks hold, and not held apart by a joint; two bodies standing still never meet. Each step, a pair of a moving body is met again, within a speculative margin of 2 centimeters, and dropped where their grown boxes part. Its contact keeps the impulses that held its bodies apart at each point, matched to the next step's points by the features that met, so a stack begins each step pushing as it ended the last. A grid's pair has a contact for each solid cell met, and a mesh's for each face of triangles met, those facing one way taken as one, their points together and the four holding the most of them kept, as Jolt takes them, so a box resting across a seam is pushed as on one face rather than one triangle's after the other's. Sensors' pairs only note whether they overlap. What began and stopped touching is told as `contact_event`s of the step, and `each_touching` visits each pair touching as the step left it, so what began and stopped since any step before is known however colliders were taken away and attached between. +- **The soft step**: a step is solved as Box2D's soft step solves one, in four substeps, each of which moves each body's velocities by its forces and gravity, pushes the bodies' velocities apart where they meet, moves them, and pushes again without undoing overlaps, the relax, so what was pushed out doesn't fly. A contact pushes as a stiff, damped spring of 30 cycles a second, damped ten times over, twice as stiff against what doesn't move, so an overlap is undone over a few substeps, no faster than 3 meters a second, and a stack doesn't jitter; a point apart within the margin pushes only as much as closes the gap in the substep, so what falls stops at what's below it, not in it. Where it moved, each point's separation is worked out again from how far its body has moved and turned since the step began, not met again. Friction holds each point along its tangent, in space along two, no harder than the friction, mixed as the square root of the two colliders', times what pushes it apart; and what met faster than 1 meter a second bounces back, at its points that pushed, as much as the greater restitution keeps. +- **Eight at once**: each step sorts its contacts into 24 colors, each given the first color none of its dynamic bodies has yet, so no two contacts of a color push one body, and solves each color's as the lanes of `f32x8`s, eight contacts at once, each body's velocities gathered from where its state lies and scattered back, as Box2D's wide solver does; the rare contact fitting no color is solved one at a time after. In space, each point's levers are packed with its bodies' inverse inertias, as each is turned as the step begins, worked into them, so the lanes turn a body by what's packed rather than by a matrix, and friction's circle is kept by each lane's square root, as `simd` has none. A lane of what doesn't move, or of a kinematic body, is gathered but never written back. The colors solve contacts in another order than one at a time would, which gives the same bits as solving them one at a time in that order. +- **Several threads**: a space's `threads`, 1 at first, solves each step on so many threads, its caller's among them, kept until the space closes, spinning between a step's jobs, as they come microseconds apart, before sleeping: the lanes of each color are split between them, a color after another, as none of a color push one body, and where two shapes meet is found for each pair at once, then put to use a pair at a time. Joints, contacts of no color, and the rest run on the caller's alone, so a step gives the same bits on any number of threads. +- **How far apart**: `gap_between` finds how far apart two shapes are, and their nearest places, as Gilbert, Johnson, and Keerthi's GJK finds them: the place of the shapes' difference nearest the origin, by a triangle of its corners at most in a plane, as Box2D's does, and a tetrahedron in space, as Ericson's regions keep it, each pass adding the corner furthest toward the origin; of each shape's core, then less their radii. A triangle or tetrahedron gone flat, as a capsule's ends level over a box's face make one, is taken by its nearest edge or face, as large as the shapes are, and the search stops where the nearest place nears no further. +- **Casts and sweeps**: `shape_cast` moves a shape along a motion as far as the gap between it and another, over how fast it closes it, says it can't yet meet it, again and again, as Mirtich's conservative advancement does, so it stops within its tolerance of where they first meet, never past it; and `time_of_impact` does the same of two shapes each swept through a step, moving and turning, as fast as each turns times how far its surface reaches from its center bounding how fast it closes. Of a space, `shape_cast` casts a shape among its colliders, sensors, a body of its own, and chains' segments and one-way colliders it begins behind passed over, and `overlap` visits each collider a shape overlaps. Each, and `ray_cast`, takes a mask of layers, or a `query_filter`: its mask, whether sensors are met, and the data of colliders passed over, as the asker's own. +- **Continuous collision**: a dynamic body that moved further in a step than half the least its shapes reach from their middles is swept, from where it began the step to where it ended it, against what stands still, a grid's cells and a mesh's or heightfield's triangles among it, a triangle only where the body reaches its plane by the step's end from in front of it, and put back where it first comes within the slop of what it meets, its velocity kept, so the next step's contacts stop it there, as Box2D's continuous collision does. Where it touches something as the step begins, as a corner resting on the ground does, a small circle or sphere about its middle is swept instead, so its middle never passes through. A `bullet` is swept against what moves too, where it ended the step, after the rest. Continuous collision is on at first, as a space's `continuous` says. +- **Impacts**: what meets faster than twice the push speed is stopped before the substeps begin, over four passes, as far as closes its gap through the step, and what stopped it is kept apart from the impulses the substeps begin with: solved within them, the impulse stopping it would be given again as each substep begins and taken back unevenly between its points, throwing a crate dropped flat. It counts toward its bounce. +- **Hits**: each pair that begins touching faster than the space's `hit_speed`, a meter a second at first, is told as a `hit_event` of the step: its colliders, where, the normal, and how fast they met, as Box2D's hit events are, for sounds of things landing. +- **Chains and one-way colliders**: a chain's segments, as `space::attach_chain` makes them, are each a collider of their own, met only on the side their normals face, to the right going along the chain, as a polygon's counterclockwise edges face out; where two join flat or hollow, neither pushes by the corner they share, so a body slides across the joints as along one surface, and where they join at a corner sticking out, the segment after it pushes by the corner, as far around it as their faces turn. Rays and casts pass a segment from behind. A collider made `one_way` is solid only to what comes onto it from the side its `up` faces: a contact beginning from below or beside it passes through until the two part, as a platform jumped through from below is. +- **Heightfields**: a `heightfield` holds a terrain's heights on a grid along x and z, two triangles of each square of four, made as they're met rather than kept, which a space keeps as it keeps a mesh's triangles, its edges two share flat or hollow passed over as a mesh's are, worked out of the heights beside them; a ray passes from square to square along x and z, as Amanatides and Woo pass one. +- **Characters**: a `character` is a body a game walks, as Jolt's virtual character is: a capsule moved through a space by casts rather than a body of it, pushed out of what overlaps it first, as what moves into it does; then cast along its motion, sliding along what it meets, and along a wall it can't walk up across it, not up it; stepping up what's no higher than its `step_height`, raised, moved on as far as it walks, and set down, where feeling further ahead than its round foot reaches finds ground it may stand on, higher than it stands; kept to the ground walking down, as far as its `snap`; riding what it stands on, by how fast that moves where it stands; and pushing what's dynamic before it, by no more than its `push`. Ground steeper than its `max_slope` isn't stood on. It stands along its `up`, which way is up against gravity, its capsule turned from y to stand along it, as `pose()` gives it, so a game turning `up` as it goes walks it around a world. Its `body`, where it's given one, as a kinematic body moved with it so what's dynamic meets it, is passed over by its own casts. +- **Joints**: a joint holds two bodies at anchors of their own, and its bodies don't meet but where it says they do. A revolute joint, or a hinge in space, holds them at a point, a hinge about an axis of each too, with limits to how far it turns, a motor turning it at a speed with as much torque as it's given, and a spring toward where it rests; a distance joint keeps two points as far apart as its length, as a rod, or between its limits, as a rope, or springily; a weld, or a fixed joint, holds them as one, rigidly or springily; and a ball joint holds them at a point they turn about every way, or, limited, as `space::cone_twist` makes one, swinging no further than a cone about an axis and twisting about it between two angles, as a shoulder. In a plane, a prismatic joint lets them slide along an axis, turning together, between limits, by a motor, or springily, as Box2D's does; a wheel holds them to an axis on a spring, its motor turning the wheel; a motor joint drives one toward a place and an angle of the other's, by no more than so much force and torque, as a character steered; and a mouse joint pulls a place of a body toward a target, as a mouse drags it. In space, a slider slides as a prismatic joint does; and a six-way joint holds each way its bodies move and turn, along and about its frame's three axes, locked, limited, or free, each driven at its own speed by no more than its own force, a joint's turn taken as a swing after a twist about its x axis, as Jolt's swing-twist joints take it, the swing's axes kept across the twist's, so a twist driven while it's swung turns freely. Changing a joint stops what it no longer asks, a motor, limits, or a spring turned off, from pushing. Joints are solved before contacts in each substep, softly, as stiff springs of 60 cycles a second, and a limit pushes as a contact does, only as much as closes it where it's apart. A pin's and a hinge's limits, motor, and spring push as hard as turning the body about the joint, its mass as far from it as its center is, takes, not about its center, so a door striking its stop stops there, rather than the point the joint holds it at turning it back. +- **Sleep**: bodies touching or joined are an island, found anew each step, and an island sleeps when all its bodies have moved slower than 5 centimeters a second, at their farthest, for half a second. A sleeping body costs nothing: its pairs aren't met again, and the solver passes it over. It wakes, with its island, where a force, an impulse, or a velocity is given it, where what touches it is awake and moving, where a joint is made or taken from it, or where what it rested on is taken away. A kinematic body sleeps alone, when it's been still as long, and keeps what rests on it awake while it moves. +- **Units**: lengths are a game's own, and a space's tolerances, its slop, margins, push speed, bounce threshold, and top speed of 400 meters a second, are made for a meter; `space::new` takes how many of a game's lengths a meter is, so a game of pixels keeps its tolerances as many meters. +- **Nothing fused**: a product is rounded before it's added, not fused with the sum as `fma` does. FMA3 works a fused sum as one instruction, but a column waiting on the sum before it is slower than one adding products worked at once: `mat4 * mat4` took 39 cycles fused, against 32, and `transform_point` 7 against 6. The same bits would also have the machine work each fused sum as `std::math::fma` does without FMA3, many instructions for one. + +## Speed +`blossom run malunal.linear.bench` works each operation over 1,024 values 2,000 times, each pass a function of its own, as a system is, its operations called from elsewhere too, built with `-O2`, here on an i5-13420H held at 2.1 GHz by its low-power profile, against the same worked a number at a time on a `vec3` of 12 bytes, as hearth's scenes worked them before `linear`. They need the compiler of 2026-10-28 or later, which works `f32`s in single precision and splats a number into lanes with one instruction; before it, what a matrix made of a vector was faster a number at a time. + +| What | Before | `linear` | | +|---|---|---|---| +| `p + v * dt` of `vec3`s | 9.66 ns | 2.00 ns | 4.8x | +| `dot` of `vec3`s | 3.83 ns | 3.84 ns | 1.0x | +| `vec3::normalized` | 13.4 ns | 2.85 ns | 4.7x | +| `quat * vec3` | 68.6 ns | 24.9 ns | 2.8x | +| `mat4 * mat4` | 35.7 ns | 13.5 ns | 2.6x | +| `mat4::transform_point` | 11.1 ns | 2.67 ns | 4.2x | +| `mat3 * mat3` | 42.0 ns | 5.26 ns | 8.0x | +| `quat * quat` | 16.8 ns | 15.3 ns | 1.1x | +| `vec3::cross` | 11.2 ns | 12.8 ns | 0.88x | +| `mat3 * vec3` | | 2.64 ns | | +| `mat4 * vec4` | | 2.95 ns | | +| `mat4::inverse` | | 96.4 ns | | + +What works whole vectors gains most, and what a matrix makes of a vector with it: integrating places by velocities, as physics does for every body, is nearly five times as fast, and `mat3 * mat3` eight. What builds a `vec3` a number at a time, as `cross` does, runs about as it did of 12 bytes, since the caller reads the 16 bytes back at once, which waits on the numbers written one at a time. How fast the same operation runs hangs on the code around it, by as much as three times either way, as code inlined into a large function slows; these are of small functions, as a game's systems are. hearth's scenes turning 2,000 entities' transforms, a rotation's product, `normalized`, and a `mat4` composed for each, took 42.7 ns an entity on a Ryzen 9 9950X3D, as they did before `linear`, with the compiler before 2026-10-28. + +`blossom run malunal.geometry.bench` times `geometry`'s tests the same way, here on battery, in the low-power profile, the best of five runs, against the same written a number at a time on a `vec3` of 12 bytes, a plane at a time, and with `math::min` and `math::max`: + +| What | Before | `geometry` | | +|---|---|---|---| +| `frustum::overlaps` of `bounds` | 20.3 ns | 10.0 ns | 2.0x | +| `frustum::overlaps` of a `sphere` | 7.38 ns | 4.50 ns | 1.6x | +| `ray::hit` of `bounds` | 61.2 ns | 19.7 ns | 3.1x | +| `ray::hit` of a `sphere` | 10.9 ns | 12.0 ns | 0.91x | +| `bounds::transformed` | 25.2 ns | 22.1 ns | 1.1x | + +Culling a scene's boxes by a camera's frustum, which a renderer does for everything it might draw, is twice as fast, of four planes at once: of eight, as one `f32x8`, it was no faster than a plane at a time, and in one build twice as slow, as the compiler moves vectors of 32 bytes through memory a half at a time where a function works several. A ray meeting a box is three times as fast for comparing its numbers. A ray meeting a sphere works as the plain code does, but gives a `maybe`, which the compiler returns through memory. + +`malunal.physics2d.bench` steps two of Box2D v3.2's benchmark scenes, built as its benchmark builds them, and `malunal.physics3d.bench` two of Jolt v5.6's performance test scenes, each built as it builds them, each on one thread and then on eight; Box2D and Jolt were built with GCC 16.2 at `-O2`, each on one thread, Box2D with its SIMD both on, AVX2, and off, and every time is of a step at 60 steps a second, on a Ryzen 9 9950X3D: + +| Scene | Box2D, AVX2 | Box2D, no SIMD | Jolt | `physics2d` or `physics3d` | On 8 threads | | +|---|---|---|---|---|---|---| +| `large_pyramid`: 5050 boxes, 100 at the base, 500 steps | 0.97 ms | 2.45 ms | | 7.4 ms | 3.8 ms | 3.0x Box2D's scalar, on one thread | +| `many_pyramids`: 400 pyramids of 55 boxes, 200 steps | 3.9 ms | 9.4 ms | | 31.4 ms | 14.2 ms | 3.3x | +| `Pyramid`: 1240 boxes in 15 tiers, 500 steps | | | 6.17 ms | 23.0 ms | 8.7 ms | 3.7x Jolt's | +| `ConvexVsMesh`: 1764 shapes onto 20000 triangles, 500 steps, sleeping | | | 2.09 ms | 13.8 ms | 11.0 ms | 6.6x | + +These are with the compiler of 2026-10-31, contacts in space solved as lanes, and continuous collision on, as it is at first; with that of 2026-10-30, and contacts in space one at a time, they were 11.9, 47.4, 41.3, and 17.1 ms. Solving Jolt's pyramid's contacts as lanes took its step from 30.2 ms to 23.0; continuous collision costs `ConvexVsMesh` about a millisecond of its 13.8, the shapes falling onto the terrain swept against its triangles, where Jolt's scene sweeps none. On eight threads every scene ends to the bit as it does on one. + +Stacks stand about as Box2D's do. Box2D's large pyramid ends its 500 steps with its top box 0.74 meters lower, squeezed, and 0.27 meters to one side, after 0.77 at the hundredth step; `physics2d`'s with its top 0.84 lower and 0.88 to one side, the colors' order of solving pushing it the way it goes, as one at a time in that order does to the bit. Of the many pyramids, the last one's top box ends within 8 millimeters of where it began; and in Jolt's pyramid, physics3d's top box settles within 6 millimeters of the height its tiers stack it to, 13 centimeters aside from where it fell, where Jolt's own wasn't measured. + +The difference was the compiler's more than the solver's, and the compiler of 2026-10-31 closed some of it: it keeps small vectors, and the values a statement's temporaries hold, out of memory, so a contact solved with `vec2`s runs nearly as fast as one worked a number at a time; it works `f32`s, their comparisons, and the choices between them as `f32`s, with no branch to choose; and it keeps eight lanes in registers where the processor has AVX. What's left, as profiled: the solvers of eight lanes spill, a contact in space holding 12 vectors of its bodies' velocities alone against the processor's 16 registers; `math::min` and `math::max` of reals test for NaN and signed zeros around each; in space, meeting two boxes still calls `cross` and makes a rotation's matrix, and zeroes six kilobytes of arrays each time, and a triangle met is made a whole hull; and on several threads, a mesh's pairs are met on the caller's alone, as are joints and what's left of a substep but the colors, which keeps `ConvexVsMesh` from gaining as the rest do. + +## Testing +`blossom test` runs `tests/linear.sakura` twice: `malunal.linear.tests` on the machine, a number at a time, with every read and write checked, and `malunal.linear.lanes.tests` as an executable built with `-O2`, as lanes. Each checks the types' sizes; vectors' arithmetic, dots, crosses, lengths, and the rest; rotations turning, following one another, undone, and between; projections, and undoing them; matrices of three's rotations, scales, transposes, determinants, and inverses; values read where a struct puts them, unaligned; values written as JSON and read back; and the bits of a long chain of all of it. + +It runs `tests/geometry.sakura` the same two ways, as `malunal.geometry.tests` and `malunal.geometry.lanes.tests`: the shapes' sizes; planes through places, distances to them, and which side a box or sphere lies on; boxes and spheres holding places and boxes, meeting, grown, merged, and moved; rays meeting planes, spheres, and boxes from outside, from within, and passing by; a camera's frustum of a perspective and of an orthographic projection, its planes facing in, and what it reaches; shapes written as JSON and read back; and the bits of a long chain of all of it. The bits are folded by `math::wrapping_mul`, as FNV-1a wraps, which a checked program's own arithmetic must name. + +`malunal.photometry.tests` runs `tests/photometry.sakura`: lumens and candela of bulbs every way and gathered into cones, and of watts; lux at distances, and nits of surfaces lit by them, white and grey, and of a clear sky; exposure values of the sunny 16 rule, at another ISO, and of meters, what they multiply light by and back, and a white surface and a grey card exposed as a meter reads, from moonlight to sunlight; and the colors of a warm bulb, of daylight, and of a blue sky, bluer as hotter all the way, and past either end as either. + +`malunal.physics2d.tests` runs `tests/physics2d.sakura`: rotations and poses, within one another and found again; boxes' corners and normals, polygons around places, leaving out what's within and along their edges, and none of a line or of nine corners, capsules, pills, the boxes holding turned shapes, and what they hold; circles meeting circles, touching, and apart, a ball on a box's face, by its corner, and within it, both ways around, and a ball by a capsule's side; a box resting on a slab at two points, apart, and the other way around, a crate on its corner at one, a capsule lying on the slab at two and standing by its corner at one, capsules side by side and crossing, and a segment across a box; rays meeting a ball, from within it, passing by, and short of it, a turned box, a capsule's side and end, and a segment from either side; 500 boxes in a tree, sound, moved and half removed, found as a brute search finds them, the nearest along a ray, and every one removed; and a grid's floor and wall met, a box resting across two cells, sunk over a seam, the face the cells share passed over, against the wall, the grid placed elsewhere, and rays into its floor and wall, from outside it, short of it, and from within a cell. + +`malunal.physics3d.tests` runs `tests/physics3d.sakura`: poses, within one another, found again, and undone; boxes' faces facing out, each edge between two at right angles, turned and moved; hulls around a cube's corners and places within it, on its faces, and along its edges, of six square faces, a tetrahedron, and an icosahedron of 20 triangles, and none of flat places or of 40 corners; triangles, flat; spheres and capsules meeting, touching, apart, and within a margin, capsules lying along one another at two points and crossing at one; a ball on a box's face, by its edge, by its corner, within it, both ways around, and over a turned box; a capsule lying on a box at two points, standing by its edge at one, and stood within it; a crate resting on a slab at four points, apart, within a margin, the other way around, and turned, on its edge at two, on its corner at one, and edge across edge at one; rays meeting a ball, a turned box, and a capsule's side, along and across it, and its end; 500 boxes in a tree, as in `physics2d`'s; and a room of triangles, a floor of 128 and a wall: a crate resting across four squares, a ball sunk beside a seam pushed up by every triangle, against the wall, and in its corner, and rays into its floor, from below it, and into its wall. Then, against searches of their own: 400 pairs of boxes and of hulls of places, turned every way, met where no axis of every face and every pair of edges parts them, and as deep as the axis parting them least, to within the faces taken over others as good; and 200 spheres and capsules against turned boxes, met as their nearest places say, a capsule's found among a thousand along its segment. + +`malunal.physics2d.tests` runs `tests/space2d.sakura` too: the masses of boxes, circles, capsules, and shapes moved off their bodies' origins, and two summed; a box dropped onto the ground, resting on it, still, and touching it once; a tower of ten boxes standing still; bodies sleeping, woken by a blow with what they rest on but not what's apart, and what rested on a body taken away waking and falling; a ball bouncing as high as it fell, and on a slope of 30 degrees a box of friction staying and one of none sliding; a body on a layer the ground's mask doesn't hold falling through, and a sensor noting a stone falling through it, and a kinematic body walking through it but not a post standing beside it; queries passing over sensors unless asked, and the asker's own; a kinematic lift carrying a crate; a pendulum keeping its length, a wheel turned by its motor, a door stopped by its limit, a rod, and a weld; a box sliding across a grid's floor of 40 cells without catching at its seams, stopped by its wall; and rays. + +`malunal.physics2d.tests` runs `tests/motion2d.sakura`, `tests/joints2d.sakura`, and `tests/character2d.sakura` too: gaps between boxes side by side, a ball off a box's corner, and a turned box beside a capsule; casts of a ball at a wall, short of it, away from it, and begun within it, and of a box onto a box turned on its corner; a stick's time of impact turning under a shelf, and one moving away; a ball thrown at a thin wall faster than it's thick each step stopping at it, swept, and passing it, not; a crate dropped flat at 200 meters a second landing on a floor as thin as a line, and dropped on its corner, thrown about but never through it; a bullet striking a thin plank, and a shot that isn't passing through it; a crate sliding along a chain of 40 segments as along one floor, a ball rising through a chain from below, and rays through it each way; a ball thrown up through a one-way ledge and landing on it; which colliders a ball overlaps, on which layers, and casts meeting a grid's cell and a crate; a tower struck by a ball ending to the bit alike on one thread and on four; a block on a prismatic joint slid by its motor to its limit, a cart riding wheels on their springs and driven by their motors, a puck driven by a motor joint to a place and an angle, and a crate dragged by a mouse joint; and characters walking, stepping up a stair but not a wall, up a gentle slope but not a steep one, riding a lift, jumping up through a one-way platform onto it, walking a bumpy chain, and walking around a world, up away from its middle; and a rock pulled by a gravity of its own onto a world's side, sleeping there, and waking as its pull turns. + +`malunal.physics3d.tests` runs `tests/space3d.sakura` the same: boxes', balls', hulls', and capsules' masses and inertia tensors, and two summed; and in space, as in a plane, a box dropped, a tower, sleeping and waking, bouncing and sliding, layers and sensors, a kinematic lift, a ball joint's pendulum, a wheel turned by a hinge's motor, a door swung against its hinge's limit, stopped there, a rod and a fixed joint; a box sliding across a mesh's floor of 800 triangles without sinking, bouncing, slowing, or turning at its seams; and rays meeting shapes and a mesh's triangle. + +It runs `tests/motion3d.sakura` and `tests/character3d.sakura` too: gaps in space, of boxes, a ball off a corner, and a capsule over a turned box's edge; casts of a ball at a wall and of a box onto a box on its corner; a ball thrown through a thin wall, swept and not, and a crate dropped onto a mesh's floor at 150 meters a second landing flat; which colliders a ball overlaps, and casts meeting a mesh's triangle and a crate; a terrain's heights, between them, and beyond it, a ray down onto it, and a ball rolling off a bump on it, never sunk; a slider driven to its limit along a diagonal; an arm on a ball joint sagging to its cone, and a bar spun about its length stopped by its twist; six-way joints holding a beam as a fixed joint does, its twist driven and its swing limited, and a car freed along a slope; a tower ending alike on one thread and on four; and characters walking a floor, stepping up a stair 30 centimeters high but not a block 60 high, up a ramp of 20 degrees but not one of 63, sliding along a wall, riding a platform, pushed by a wall, pushing a crate, and walking around a world, standing along its up; and a rock pulled by a gravity of its own onto a world's side, sleeping there, and waking as its pull turns. + +## Not yet +Vectors of several values at once, as eight `vec3`s in three `f32x8`s, which physics passes over its bodies with, and which the bench's own tries found ten to twenty times as fast as one at a time; `f64` vectors; and `vec2`s worked as lanes, which hold half an `f32x4`. Of `geometry`: triangles, capsules, and boxes turned with what they hold, and rays and the tests between them; testing many boxes against a frustum at once, their numbers lanes of several; and the frustum of a projection whose depth runs the other way, or without end. Of `photometry`: radiometric units and spectra, and luminance of what a camera sees, for exposure that adapts. Of `physics2d`: rounded polygons; rolling resistance and moving surfaces, as a conveyor's; and a body's colliders cast as one. Of `physics3d`: cylinders, rounded hulls, and hulls of more than 32 corners, made fewer; a mesh's triangles kept by a tree built once, from the top down, rather than one inserted at a time, and a triangle met without making a whole hull of it each time; a mesh's pairs met on several threads; turning bodies' gyroscopic torque; and a character's own up other than its space's, and its crouching. Of both: islands put to sleep and joints solved on several threads; and the speed Box2D and Jolt reach, which waits on what sakurac makes of lanes of eight and the arrays it zeroes. \ No newline at end of file diff --git a/blossomfile b/blossomfile new file mode 100644 index 0000000..fa7fd61 --- /dev/null +++ b/blossomfile @@ -0,0 +1,181 @@ +name: physics +gpid: malunal +semv: 1.0.0 + +options: + level: 2 + +requires: +- https://git.malunal.studio/sakura/std@v1.0.0 + +targets: +- name: malunal.linear + type: library + root: ./linear + deps: + - std.math + - std.serial + +# The shapes of space, made of `malunal::linear`'s vectors, and the tests +# between them. +- name: malunal.geometry + type: library + root: ./geometry + deps: + - malunal.linear + - std.math + - std.serial + +# Light in the units it's measured in, lumens, candela, lux, and nits, and +# converted between them; exposure values; and the colors of temperatures. +- name: malunal.photometry + type: library + root: ./photometry + deps: + - malunal.linear + - std.math + +# What collides and moves in a plane: shapes, where and how deep two meet, +# rays, a tree of boxes, a grid of solid cells, as a tilemap's walls are, and a +# space of bodies pushed by forces and what they meet, and held by joints. +- name: malunal.physics2d + type: library + root: ./physics2d + deps: + - malunal.linear + - std.containers + - std.math + - std.serial + - std.thread + - std.time + +# What collides and moves in space: shapes, where and how deep two meet, rays, +# a tree of boxes, the triangles of a surface, as a level's ground and walls +# are, and a space of bodies pushed by forces and what they meet, and held by +# joints. +- name: malunal.physics3d + type: library + root: ./physics3d + deps: + - malunal.geometry + - malunal.linear + - std.containers + - std.math + - std.serial + - std.thread + - std.time + +# Times what `malunal::linear` does against the same written a number at a +# time; see its header. +- name: malunal.linear.bench + type: program + level: ${level} + deps: + - malunal.linear + - std.containers + - std.io + - std.math + - std.time + srcs: + - tools/bench.sakura + +# Times what `malunal::geometry` does against the same written a number at a +# time; see its header. +- name: malunal.geometry.bench + type: program + level: ${level} + deps: + - malunal.geometry + - malunal.linear + - std.containers + - std.io + - std.math + - std.time + srcs: + - tools/geometry_bench.sakura + +# Steps `malunal::physics2d`'s space through Box2D's benchmark scenes; see its +# header. +- name: malunal.physics2d.bench + type: program + level: ${level} + deps: + - malunal.linear + - malunal.physics2d + - std.containers + - std.io + - std.math + - std.time + srcs: + - tools/physics2d_bench.sakura + +# Steps `malunal::physics3d`'s space through Jolt's performance test scenes; +# see its header. +- name: malunal.physics3d.bench + type: program + level: ${level} + deps: + - malunal.geometry + - malunal.linear + - malunal.physics3d + - std.containers + - std.io + - std.math + - std.time + srcs: + - tools/physics3d_bench.sakura + +tests: +# On the machine, which works each number at a time. +- name: malunal.linear.tests + type: program + deps: [malunal.linear, std.json, std.math, std.serial, std.testing] + srcs: [tests/main.sakura, tests/linear.sakura] + +# The same tests built with `-O2`, which works vectors as lanes, and gives the +# same bits. +- name: malunal.linear.lanes.tests + type: program + runs: native + level: 2 + deps: [malunal.linear, std.json, std.math, std.serial, std.testing] + srcs: [tests/main.sakura, tests/linear.sakura] + +# `malunal::geometry`'s, the same two ways. +- name: malunal.geometry.tests + type: program + deps: [malunal.geometry, malunal.linear, std.json, std.math, std.serial, std.testing] + srcs: [tests/main.sakura, tests/geometry.sakura] + +- name: malunal.geometry.lanes.tests + type: program + runs: native + level: 2 + deps: [malunal.geometry, malunal.linear, std.json, std.math, std.serial, std.testing] + srcs: [tests/main.sakura, tests/geometry.sakura] + +- name: malunal.photometry.tests + type: program + deps: [malunal.linear, malunal.photometry, std.math, std.testing] + srcs: [tests/main.sakura, tests/photometry.sakura] + +- name: malunal.physics2d.tests + type: program + deps: [malunal.linear, malunal.physics2d, std.containers, std.math, std.testing] + srcs: [tests/main.sakura, tests/physics2d.sakura, tests/space2d.sakura, tests/motion2d.sakura, tests/joints2d.sakura, tests/character2d.sakura] + +- name: malunal.physics3d.tests + type: program + deps: [malunal.geometry, malunal.linear, malunal.physics3d, std.containers, std.math, std.testing] + srcs: [tests/main.sakura, tests/physics3d.sakura, tests/space3d.sakura, tests/motion3d.sakura, tests/character3d.sakura] + +exports: +- malunal.linear +- malunal.geometry +- malunal.photometry +- malunal.physics2d +- malunal.physics3d + +package: + desc: The numbers of physical space and what's in it. Vectors, quaternions, and matrices of f32, and the shapes of space made of them, worked as SIMD lanes where an executable holds them; light in the units it's measured in; and what collides and moves in a plane and in space, as rigid bodies. + auth: John Christman diff --git a/geometry/bounds.sakura b/geometry/bounds.sakura new file mode 100644 index 0000000..3029eaa --- /dev/null +++ b/geometry/bounds.sakura @@ -0,0 +1,121 @@ +#! Contains `bounds`, a box along the axes: the least corner and the greatest of +#! what it holds, as of a mesh, a body, or a part of a scene, so whether two +#! meet, or a ray or a camera reaches one, is a few comparisons. + +import std::math; +import std::serial; +import malunal::linear; +module malunal::geometry; + +#! A box along the axes, from its least corner to its greatest. +@serial +pub struct bounds { + @serial pub var min: vec3; + @serial pub var max: vec3; +} + +#! The box holding nothing, from infinity to minus infinity, which takes the +#! place or box it's first grown by. +pub val bounds::blank := bounds{ + vec3{ math::infinity::(), math::infinity::(), math::infinity::() }, + vec3{ -math::infinity::(), -math::infinity::(), -math::infinity::() }, +}; + +#! The box of a center, reaching so far from it along each axis. +pub def bounds::around(center: vec3, half_size: vec3): bounds { + return bounds{ center - half_size, center + half_size }; +} + +#! The least box holding places, or `blank` of none. +pub def bounds::of(points: span): bounds { + var made := bounds::blank; + for p in points { + made = made.including(p); + } + return made; +} + +#! The least box holding a sphere. +pub def bounds::of(s: sphere): bounds { + return bounds::around(s.center, vec3{ s.radius, s.radius, s.radius }); +} + +pub val bounds::center: vec3 { + get => (this.min + this.max) * 0.5; +} + +pub val bounds::size: vec3 { + get => this.max - this.min; +} + +#! How far it reaches from its center along each axis. +pub val bounds::half_size: vec3 { + get => (this.max - this.min) * 0.5; +} + +#! Whether it holds nothing, as `blank` does: a least corner past its greatest. +pub val bounds::empty: bool { + get => this.min.x > this.max.x || this.min.y > this.max.y || this.min.z > this.max.z; +} + +pub def bounds::equals(&this, other: &bounds): bool { + return this.min == other.min && this.max == other.max; +} + +#! Whether a place is within it. +pub def bounds::contains(&this, p: vec3): bool { + return p.x >= this.min.x && p.y >= this.min.y && p.z >= this.min.z + && p.x <= this.max.x && p.y <= this.max.y && p.z <= this.max.z; +} + +#! Whether another box is within it whole. +pub def bounds::contains(&this, other: bounds): bool { + return this.contains(other.min) && this.contains(other.max); +} + +#! Whether it and another box meet. +pub def bounds::overlaps(&this, other: bounds): bool { + return this.min.x <= other.max.x && this.min.y <= other.max.y && this.min.z <= other.max.z + && this.max.x >= other.min.x && this.max.y >= other.min.y && this.max.z >= other.min.z; +} + +#! Whether it and a sphere meet. +pub def bounds::overlaps(&this, s: sphere): bool { + return s.overlaps(this); +} + +#! Its place nearest another: the place itself where it's within. +pub def bounds::closest(&this, p: vec3): vec3 { + return p.max(this.min).min(this.max); +} + +#! The box grown to hold a place too. +pub def bounds::including(&this, p: vec3): bounds { + return bounds{ this.min.min(p), this.max.max(p) }; +} + +#! The least box holding it and another. +pub def bounds::merged(&this, other: bounds): bounds { + return bounds{ this.min.min(other.min), this.max.max(other.max) }; +} + +#! The least box along the axes holding this one moved, turned, and scaled by a +#! matrix that doesn't project: its center moved, and its reach along each of +#! its own axes turned, each number made positive, and added. +pub def bounds::transformed(&this, by: mat4): bounds { + return bounds::blank if this.empty; + val half := this.half_size; + val m := &by.m; + if lanes_held() { + # Each column as lanes, read where it lies, as `mat4`'s products read them. + val reach := lanes_at(&m[0]).abs() * f32x4::splat(half.x) + lanes_at(&m[4]).abs() * f32x4::splat(half.y) + + lanes_at(&m[8]).abs() * f32x4::splat(half.z); + return bounds::around(by.transform_point(this.center), vec3::of_lanes(reach)); + } + val reach := vec3{ + math::abs(m[0]) * half.x + math::abs(m[4]) * half.y + math::abs(m[8]) * half.z, + math::abs(m[1]) * half.x + math::abs(m[5]) * half.y + math::abs(m[9]) * half.z, + math::abs(m[2]) * half.x + math::abs(m[6]) * half.y + math::abs(m[10]) * half.z, + }; + return bounds::around(by.transform_point(this.center), reach); +} diff --git a/geometry/frustum.sakura b/geometry/frustum.sakura new file mode 100644 index 0000000..ba78d1c --- /dev/null +++ b/geometry/frustum.sakura @@ -0,0 +1,137 @@ +#! Contains `frustum`, the part of space a camera sees: the six planes bounding +#! what a projection draws, each facing in, and whether a place, a box, or a +#! sphere is within them, so a renderer draws only what might be seen. The +#! planes' numbers are lanes, so an executable holding vectors in registers +#! tests four planes at once, then the other two: as two vectors of four, which +#! it holds in registers as it works them, where one of eight went through +#! memory a half at a time, twice as slow. + +import malunal::linear; +module malunal::geometry; + +#! The part of space a camera sees, within six planes facing in: left, right, +#! bottom, top, near, and far. It holds their normals' `x`s, `y`s, and `z`s, and +#! how far the origin is in front of each, eight of each, read as two `f32x4`s; +#! the last two are of planes of zeros, which nothing is behind. +pub struct frustum { + var _x: f32[8]; + var _y: f32[8]; + var _z: f32[8]; + var _d: f32[8]; +} + +#! The frustum of what a matrix projects into its clip space, its planes in the +#! space it projects from: of `projection * view`, the world's, and of a +#! projection alone, the camera's. Clip space bounds x and y between -w and w, +#! and depth between 0 and w, so each plane is the matrix's row of w with +#! another row added or taken away, and the near plane its row of depth alone. +pub def frustum::of(clip: mat4): frustum { + val m := &clip.m; + val x := vec4{ m[0], m[4], m[8], m[12] }; + val y := vec4{ m[1], m[5], m[9], m[13] }; + val z := vec4{ m[2], m[6], m[10], m[14] }; + val w := vec4{ m[3], m[7], m[11], m[15] }; + return frustum::of_planes([plane_of(w + x), plane_of(w - x), plane_of(w + y), plane_of(w - y), plane_of(z), plane_of(w - z)]); +} + +# The plane of a matrix's row: the places that, with a 1 after them, it makes +# 0 of, in front where it makes more, made of length 1. +def plane_of(row: vec4): plane { + val l := row.xyz.length; + return plane{ row.xyz / l, -row.w / l }; +} + +#! The frustum of six planes facing in: left, right, bottom, top, near, and far. +pub def frustum::of_planes(planes: plane[6]): frustum { + var made := frustum{}; + for i in 0..6u { + made._x[i] = planes[i].normal.x; + made._y[i] = planes[i].normal.y; + made._z[i] = planes[i].normal.z; + made._d[i] = -planes[i].distance; + } + return made; +} + +#! Its planes: left, right, bottom, top, near, and far. +pub val frustum::planes: plane[6] { + get { + var made: plane[6]; + for i in 0..6u { + made[i] = plane{ vec3{ this._x[i], this._y[i], this._z[i] }, -this._d[i] }; + } + return made; + } +} + +#! Whether a place is within it. +pub def frustum::contains(&this, p: vec3): bool { + if lanes_held() { + val x := f32x4::splat(p.x); + val y := f32x4::splat(p.y); + val z := f32x4::splat(p.z); + return in_front(this.ahead(0, x, y, z), this.ahead(4, x, y, z)); + } + for i in 0..6u { + return false if this._x[i] * p.x + this._y[i] * p.y + this._z[i] * p.z + this._d[i] < 0; + } + return true; +} + +#! Whether a box might be seen: whether, of each plane, the box's corner +#! furthest in front of it is in front. A box beside a corner of the frustum, +#! outside it but in front of every plane, counts as seen, which a renderer +#! draws for nothing; one it reaches always counts. +pub def frustum::overlaps(&this, b: bounds): bool { + if lanes_held() { + return in_front(this.ahead_of(0, &b), this.ahead_of(4, &b)); + } + for i in 0..6u { + val x := this._x[i] < 0 ? b.min.x : b.max.x; + val y := this._y[i] < 0 ? b.min.y : b.max.y; + val z := this._z[i] < 0 ? b.min.z : b.max.z; + return false if this._x[i] * x + this._y[i] * y + this._z[i] * z + this._d[i] < 0; + } + return true; +} + +#! Whether a sphere might be seen: whether its center is no further behind any +#! plane than its radius. As of a box, one beside a corner counts too. +pub def frustum::overlaps(&this, s: sphere): bool { + val c := s.center; + if lanes_held() { + val x := f32x4::splat(c.x); + val y := f32x4::splat(c.y); + val z := f32x4::splat(c.z); + val r := f32x4::splat(s.radius); + return in_front(this.ahead(0, x, y, z) + r, this.ahead(4, x, y, z) + r); + } + for i in 0..6u { + return false if this._x[i] * c.x + this._y[i] * c.y + this._z[i] * c.z + this._d[i] + s.radius < 0; + } + return true; +} + +# How far places, a lane each, are in front of four planes from one, as lanes. +def frustum::ahead(&this, first: u64, x: f32x4, y: f32x4, z: f32x4): f32x4 { + return lanes_at(&this._x[first]) * x + lanes_at(&this._y[first]) * y + lanes_at(&this._z[first]) * z + lanes_at(&this._d[first]); +} + +# How far a box's corner furthest in front of each of four planes from one is +# in front of it, as lanes. +def frustum::ahead_of(&this, first: u64, b: &bounds): f32x4 { + val zero := f32x4::splat(0); + val x := lanes_at(&this._x[first]); + val y := lanes_at(&this._y[first]); + val z := lanes_at(&this._z[first]); + return x * select(x.less(&zero), f32x4::splat(b.min.x), f32x4::splat(b.max.x)) + + y * select(y.less(&zero), f32x4::splat(b.min.y), f32x4::splat(b.max.y)) + + z * select(z.less(&zero), f32x4::splat(b.min.z), f32x4::splat(b.max.z)) + lanes_at(&this._d[first]); +} + +# Whether something is in front of each of eight planes, by how far it's in +# front of each, as lanes. +def in_front(first: f32x4, last: f32x4): bool { + val zero := f32x4::splat(0); + return (first.less(&zero) | last.less(&zero)).none(); +} diff --git a/geometry/geometry.sakura b/geometry/geometry.sakura new file mode 100644 index 0000000..e588eee --- /dev/null +++ b/geometry/geometry.sakura @@ -0,0 +1,51 @@ +#! Contains `geometry`: the shapes of space, made of `linear`'s vectors, and +#! what games, their renderers, and their physics ask of them: where a ray first +#! meets a plane, a sphere, or a box, which side of a plane something lies on, +#! whether boxes and spheres meet or hold a place, and whether a camera's +#! frustum reaches something, so only what it might see is drawn. +#! +#! Space is `linear`'s: right-handed, y up, and a camera looking down its -z. A +#! frustum is of a matrix's clip space as `linear`'s projections make it, depth +#! from 0 at the near plane to 1 at the far one. +#! +#! Each shape is of `linear`'s vectors and plain `f32`s, worked as lanes where +#! `linear` works them, and a frustum holds its six planes' numbers a lane +#! each, so an executable optimized with `-O2` tests a place, a box, or a sphere +#! against four planes at once, then the other two. What gives a number of a +#! few, as a dot product does, is a number at a time, as `linear`'s `cross` is: +#! lanes taken apart to be added, then worked as numbers, ran two to three times +#! as slow. The virtual machine works everything a number at a time, in the order +#! the lanes do, so either way gives the same answers and the same bits. +#! +#! A place exactly on a shape's surface is within it: a box holds its corners, +#! a sphere the places at its radius, and two boxes touching meet. + +import malunal::linear; +module malunal::geometry; + + +# The dot product of two vectors, a number at a time, in the order `vec3::dot` +# adds them. +def dot_of(a: &vec3, b: &vec3): f32 { + return a.x * b.x + a.y * b.y + a.z * b.z; +} + +# The square of the distance between two places, a number at a time, as the +# dot product of `a - b` with itself gives it. +def distance_squared(a: &vec3, b: &vec3): f32 { + val x := a.x - b.x; + val y := a.y - b.y; + val z := a.z - b.z; + return x * x + y * y + z * z; +} + +# The lesser of two numbers, and the greater: of a NaN, either may be given, +# where `math::min` and `math::max` work three times as long to give it. +def least(a: f32, b: f32): f32 { return b < a ? b : a; } +def most(a: f32, b: f32): f32 { return a < b ? b : a; } + +# Four numbers as lanes, read from where the first lies, which needs no +# alignment. +def lanes_at(first: &f32): f32x4 { + return ((first as *f32) as *f32x4)[0]; +} diff --git a/geometry/plane.sakura b/geometry/plane.sakura new file mode 100644 index 0000000..7aa14e3 --- /dev/null +++ b/geometry/plane.sakura @@ -0,0 +1,72 @@ +#! Contains `plane`, a flat surface without end, and which side of one something +#! lies on: what bounds a frustum, a floor or a wall a ray meets, and what splits +#! a space in two. + +import std::serial; +import malunal::linear; +module malunal::geometry; + +#! A plane: the places as far along its normal, a direction of length 1, as +#! `distance`. Its front is the side the normal points to. +@serial +pub struct plane { + @serial pub var normal: vec3; + @serial pub var distance: f32; +} + +#! Which side of a plane something lies on. +pub enum side: u8 { + front, #! Wholly where the normal points. + back, #! Wholly behind. + across, #! On both sides, or touching it. +} + +#! The plane through a place, facing a direction, made of length 1. +pub def plane::through(point: vec3, normal: vec3): plane { + val n := normal.normalized(); + return plane{ n, n.dot(point) }; +} + +#! The plane through three places, facing where they turn counterclockwise, as +#! a triangle's front does. +pub def plane::of_points(a: vec3, b: vec3, c: vec3): plane { + return plane::through(a, (b - a).cross(c - a)); +} + +pub def plane::equals(&this, other: &plane): bool { + return this.normal == other.normal && this.distance == other.distance; +} + +#! How far a place is in front of the plane, negative behind it. +pub def plane::distance_to(&this, p: vec3): f32 { + return dot_of(&this.normal, &p) - this.distance; +} + +#! The plane's place nearest another. +pub def plane::closest(&this, p: vec3): vec3 { + return p - this.normal * this.distance_to(p); +} + +#! The same plane facing the other way. +pub def plane::flipped(&this): plane { + return plane{ -this.normal, -this.distance }; +} + +#! Which side of the plane a box lies on: how far its center is in front, +#! against how far the box reaches along the normal. +pub def plane::side_of(&this, b: bounds): side { + val half := b.half_size; + return side_at(this.distance_to(b.center), dot_of(&half, &this.normal.abs())); +} + +#! Which side of the plane a sphere lies on. +pub def plane::side_of(&this, s: sphere): side { + return side_at(this.distance_to(s.center), s.radius); +} + +# The side of what is centered so far in front of a plane, and reaches so far. +def side_at(at: f32, reach: f32): side { + return side::front if at > reach; + return side::back if at < -reach; + return side::across; +} diff --git a/geometry/ray.sakura b/geometry/ray.sakura new file mode 100644 index 0000000..8a63f67 --- /dev/null +++ b/geometry/ray.sakura @@ -0,0 +1,88 @@ +#! Contains `ray`, a half line from a place in a direction, and where it first +#! meets a plane, a sphere, or a box, as picking what's under a pointer, a line +#! of sight, or a shot asks. + +import std::math; +import std::serial; +import malunal::linear; +module malunal::geometry; + +#! A half line from a place in a direction. How far along it something lies is +#! counted in lengths of its direction, so it's a distance where the direction +#! is of length 1, as `toward` makes it. +@serial +pub struct ray { + @serial pub var origin: vec3; + @serial pub var direction: vec3; +} + +#! The ray from a place toward another, its direction of length 1. +pub def ray::toward(origin: vec3, target: vec3): ray { + return ray{ origin, (target - origin).normalized() }; +} + +pub def ray::equals(&this, other: &ray): bool { + return this.origin == other.origin && this.direction == other.direction; +} + +#! The place so far along it. +pub def ray::at(&this, t: f32): vec3 { + return this.origin + this.direction * t; +} + +#! Its place nearest another, from its origin on. +pub def ray::closest(&this, p: vec3): vec3 { + val d := &this.direction; + val toward := (p.x - this.origin.x) * d.x + (p.y - this.origin.y) * d.y + (p.z - this.origin.z) * d.z; + val along := toward / dot_of(d, d); + return this.at(along > 0 ? along : 0); +} + +#! How far along it it meets a plane, from either side, or none where it runs +#! beside the plane or away from it. +pub def ray::hit(&this, p: plane): maybe { + val toward := dot_of(&p.normal, &this.direction); + return nothing {} if toward == 0; + val t := p.distance_to(this.origin) / -toward; + return nothing {} if !(t >= 0); + return t; +} + +#! How far along it it first meets a sphere, 0 where it begins within, or none +#! where it passes by or away. +pub def ray::hit(&this, s: sphere): maybe { + val d := &this.direction; + val mx := this.origin.x - s.center.x; + val my := this.origin.y - s.center.y; + val mz := this.origin.z - s.center.z; + val c := mx * mx + my * my + mz * mz - s.radius * s.radius; + return 0f if c <= 0; + # Outside, and moving away from the center or across it, it never comes nearer. + val b := mx * d.x + my * d.y + mz * d.z; + return nothing {} if b >= 0; + val a := dot_of(d, d); + val e := b * b - a * c; + return nothing {} if e < 0; + return (-b - math::sqrt(e)) / a; +} + +#! How far along it it first meets a box, 0 where it begins within, or none +#! where it passes by or away: where it is between the box's faces along every +#! axis at once. One along a face, in its plane, may meet the box or pass by. +pub def ray::hit(&this, b: bounds): maybe { + # Along an axis it doesn't move along, it's between the faces everywhere, or + # nowhere, as dividing by zero gives infinities. + val ix := 1 / this.direction.x; + val iy := 1 / this.direction.y; + val iz := 1 / this.direction.z; + val x0 := (b.min.x - this.origin.x) * ix; + val x1 := (b.max.x - this.origin.x) * ix; + val y0 := (b.min.y - this.origin.y) * iy; + val y1 := (b.max.y - this.origin.y) * iy; + val z0 := (b.min.z - this.origin.z) * iz; + val z1 := (b.max.z - this.origin.z) * iz; + val enter := most(most(least(x0, x1), least(y0, y1)), most(least(z0, z1), 0)); + val leave := least(least(most(x0, x1), most(y0, y1)), most(z0, z1)); + return nothing {} if !(enter <= leave); + return enter; +} diff --git a/geometry/sphere.sakura b/geometry/sphere.sakura new file mode 100644 index 0000000..c94877e --- /dev/null +++ b/geometry/sphere.sakura @@ -0,0 +1,40 @@ +#! Contains `sphere`, the places within a distance of a center: what holds a +#! body for the quickest test of whether two might meet, their distance against +#! the sum of their radii. + +import std::serial; +import malunal::linear; +module malunal::geometry; + +#! The places within `radius` of `center`. +@serial +pub struct sphere { + @serial pub var center: vec3; + @serial pub var radius: f32; +} + +#! The least sphere holding a box: of its center, reaching its corners. +pub def sphere::of(b: bounds): sphere { + return sphere{ b.center, b.half_size.length }; +} + +pub def sphere::equals(&this, other: &sphere): bool { + return this.center == other.center && this.radius == other.radius; +} + +#! Whether a place is within it. +pub def sphere::contains(&this, p: vec3): bool { + return distance_squared(&p, &this.center) <= this.radius * this.radius; +} + +#! Whether it and another sphere meet. +pub def sphere::overlaps(&this, other: sphere): bool { + val reach := this.radius + other.radius; + return distance_squared(&other.center, &this.center) <= reach * reach; +} + +#! Whether it and a box meet: whether the box's place nearest its center is +#! within it. +pub def sphere::overlaps(&this, b: bounds): bool { + return this.contains(b.closest(this.center)); +} diff --git a/linear/linear.sakura b/linear/linear.sakura new file mode 100644 index 0000000..aa43a38 --- /dev/null +++ b/linear/linear.sakura @@ -0,0 +1,43 @@ +#! Contains `linear`: vectors of two, three, and four `f32`s, rotations as +#! quaternions, and matrices of three by three and four by four, the numbers of +#! space as games, their renderers, and their physics work it. +#! +#! Space is right-handed: x to the right, y up, and z toward the viewer, so a +#! camera looks down its own -z. A matrix is column-major, as GLSL reads one, +#! and multiplies a vector on its right: `m * v`. Projections give a clip space +#! of y up and depth from 0 at the near plane to 1 at the far one, as Vulkan's +#! is with its y flipped. Angles are radians. +#! +#! Each type is of plain `f32` fields, so it's laid out as C and the GPU lay +#! out its numbers, and the virtual machine reads a field as quickly as any. +#! `vec3`, `vec4`, and `quat` are 16 bytes, `vec3` holding a fourth number no one +#! names, so an executable optimized with `-O2`, which holds `simd` vectors in +#! registers, reads each as one `f32x4` from where it is, and works it as lanes +#! at once: adding, scaling, dots, lengths, and `normalized`, and what a matrix +#! makes of a vector or another matrix, each of its columns scaled by a number +#! splat into every lane, and added. What gathers one vector's numbers into +#! other lanes, as a cross product and a quaternions' product would, it works a +#! number at a time, as `simd::shuffle` gathers them a lane at a time. The +#! virtual machine, which works lanes one at a time, works everything a number +#! at a time, in the order the lanes do, so both ways give the same bits. +#! +#! A product is rounded before it's added, not fused with the sum as `fma` does: +#! a column waiting on the fused sum before it is slower than one adding +#! products worked at once, and the virtual machine would work each fused sum +#! as `std::math` does without FMA3, many instructions for one. + +module malunal::linear; + + +# The lanes of a value of four `f32`s, as `vec3`, `vec4`, and `quat` are, read +# from where it is, which needs no alignment. +def lanes_of(v: &T): f32x4 { + return ((v as *T) as *f32x4)[0]; +} + +# The value of four `f32`s whose numbers are lanes. +def of_lanes(lanes: f32x4): T where T: zeroable { + var made: T; + ((&mut made) as *mut f32x4)[0] = lanes; + return made; +} diff --git a/linear/mat3.sakura b/linear/mat3.sakura new file mode 100644 index 0000000..c6d60a6 --- /dev/null +++ b/linear/mat3.sakura @@ -0,0 +1,104 @@ +#! Contains `mat3`, a matrix of three by three: a rotation, a scale, or what +#! turns and stretches a direction without moving it, as an inertia tensor +#! does. Its columns are `vec3`s, each 16 bytes, so it's laid out as std140 +#! lays out a GLSL `mat3`, and its columns are added and scaled as lanes. + +import std::serial; +module malunal::linear; + +#! A matrix of three by three, column after column: where it takes x, y, and z. +@serial +pub struct mat3 { + @serial pub var x_axis: vec3; + @serial pub var y_axis: vec3; + @serial pub var z_axis: vec3; +} + +#! The matrix that changes nothing. +pub val mat3::identity := mat3{ vec3::right, vec3::up, vec3::back }; + +#! Turning by a rotation. +pub def mat3::rotation(by: quat): mat3 { + val q := by; + val xx := q.x * q.x; + val yy := q.y * q.y; + val zz := q.z * q.z; + val xy := q.x * q.y; + val xz := q.x * q.z; + val yz := q.y * q.z; + val wx := q.w * q.x; + val wy := q.w * q.y; + val wz := q.w * q.z; + return mat3{ + vec3{ 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy) }, + vec3{ 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx) }, + vec3{ 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy) }, + }; +} + +#! Scaling along each axis. +pub def mat3::scaling(by: vec3): mat3 { + return mat3{ vec3{ by.x, 0, 0 }, vec3{ 0, by.y, 0 }, vec3{ 0, 0, by.z } }; +} + +#! The matrix doing another, then this: each of the other's columns, as this +#! turns and scales it. +pub def mat3::mul(&this, other: &mat3): mat3 { + return mat3{ this * other.x_axis, this * other.y_axis, this * other.z_axis }; +} + +#! A direction the matrix turns and scales: each column, scaled by one of its +#! numbers, added. +pub def mat3::mul(&this, v: &vec3): vec3 { + if lanes_held() { + return of_lanes::(lanes_of(&this.x_axis) * f32x4::splat(v.x) + lanes_of(&this.y_axis) * f32x4::splat(v.y) + + lanes_of(&this.z_axis) * f32x4::splat(v.z)); + } + return vec3{ + this.x_axis.x * v.x + this.y_axis.x * v.y + this.z_axis.x * v.z, + this.x_axis.y * v.x + this.y_axis.y * v.y + this.z_axis.y * v.z, + this.x_axis.z * v.x + this.y_axis.z * v.y + this.z_axis.z * v.z, + }; +} + +pub def mat3::mul(&this, by: &f32): mat3 { + return mat3{ this.x_axis * by, this.y_axis * by, this.z_axis * by }; +} + +pub def mat3::add(&this, other: &mat3): mat3 { + return mat3{ this.x_axis + other.x_axis, this.y_axis + other.y_axis, this.z_axis + other.z_axis }; +} + +pub def mat3::sub(&this, other: &mat3): mat3 { + return mat3{ this.x_axis - other.x_axis, this.y_axis - other.y_axis, this.z_axis - other.z_axis }; +} + +pub def mat3::equals(&this, other: &mat3): bool { + return this.x_axis == other.x_axis && this.y_axis == other.y_axis && this.z_axis == other.z_axis; +} + +#! Its rows as its columns, which for a rotation is the rotation back. +pub def mat3::transposed(&this): mat3 { + return mat3{ + vec3{ this.x_axis.x, this.y_axis.x, this.z_axis.x }, + vec3{ this.x_axis.y, this.y_axis.y, this.z_axis.y }, + vec3{ this.x_axis.z, this.y_axis.z, this.z_axis.z }, + }; +} + +#! How much it scales a volume, negative where it mirrors one. +pub val mat3::determinant: f32 { + get => this.x_axis.dot(this.y_axis.cross(this.z_axis)); +} + +#! The matrix undoing this, or none where nothing can, as a scale of zero: each +#! row the cross product of the other two columns, over the determinant. +pub def mat3::inverse(&this): mat3 { + val a := this.y_axis.cross(this.z_axis); + val b := this.z_axis.cross(this.x_axis); + val c := this.x_axis.cross(this.y_axis); + val det := this.x_axis.dot(a); + # Scaled by 0 where nothing undoes it, so it returns once. + val k := det != 0 ? 1 / det : 0; + return mat3{ a * k, b * k, c * k }.transposed(); +} diff --git a/linear/mat4.sakura b/linear/mat4.sakura new file mode 100644 index 0000000..f8ea9ef --- /dev/null +++ b/linear/mat4.sakura @@ -0,0 +1,258 @@ +#! Contains `mat4`, a matrix of four by four: what moves, turns, and scales a +#! place, or projects it, as a camera does. Its numbers are column after +#! column, so a column is 16 bytes, read as one `f32x4`, and its products are +#! each column scaled and added at once. + +import std::math; +import std::serial; +module malunal::linear; + +#! A matrix of four by four, column after column. `std::serial` writes it as a +#! sequence of its 16 numbers, in the same order. +pub struct mat4 { + pub var m: f32[16]; +} + +pub def mat4::encode(&this, out: &mut serial::encoder): void { + out.begin_array(16); + for i in 0..16u { + serial::encode(&this.m[i], out); + } + out.end_array(); +} + +pub def mat4::decode(from: &serial::decoder, at: u32, given: serial::options): result { + if from.kind_of(at) != serial::kind::array || from.count(at) != 16 { + return serial::error::at(serial::error_kind::wrong_kind, from.place(at)); + } + var made := mat4{}; + var item: u32 = 0; + for i in 0..16u { + item = i == 0 ? from.element(at, 0) : from.next_element(at, item); + val read := serial::decode::(from, item, given) else (e) { return e; }; + made.m[i] = read; + } + return made; +} + +#! The matrix that changes nothing. +pub val mat4::identity := mat4{ m = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] }; + +#! Moving by a vector. +pub def mat4::translation(by: vec3): mat4 { + var made := mat4::identity; + made.m[12] = by.x; + made.m[13] = by.y; + made.m[14] = by.z; + return made; +} + +#! Scaling along each axis. +pub def mat4::scaling(by: vec3): mat4 { + var made := mat4::identity; + made.m[0] = by.x; + made.m[5] = by.y; + made.m[10] = by.z; + return made; +} + +#! Turning by a rotation. +pub def mat4::rotation(by: quat): mat4 { + return mat4::compose(vec3::zero, by, vec3::one); +} + +#! Scaling, then turning, then moving: what a transform does. +pub def mat4::compose(translation: vec3, rotation: quat, scale: vec3): mat4 { + val q := rotation; + val xx := q.x * q.x; + val yy := q.y * q.y; + val zz := q.z * q.z; + val xy := q.x * q.y; + val xz := q.x * q.z; + val yz := q.y * q.z; + val wx := q.w * q.x; + val wy := q.w * q.y; + val wz := q.w * q.z; + return mat4{ m = [ + (1 - 2 * (yy + zz)) * scale.x, 2 * (xy + wz) * scale.x, 2 * (xz - wy) * scale.x, 0, + 2 * (xy - wz) * scale.y, (1 - 2 * (xx + zz)) * scale.y, 2 * (yz + wx) * scale.y, 0, + 2 * (xz + wy) * scale.z, 2 * (yz - wx) * scale.z, (1 - 2 * (xx + yy)) * scale.z, 0, + translation.x, translation.y, translation.z, 1, + ] }; +} + +#! A perspective projection, as a camera's: its field of view up and down, the +#! width over the height it's drawn at, and the nearest and furthest it draws. +pub def mat4::perspective(fov_y: f32, aspect: f32, near: f32, far: f32): mat4 { + val f := 1 / math::tan(fov_y / 2); + var made := mat4{}; + made.m[0] = f / aspect; + made.m[5] = f; + made.m[10] = far / (near - far); + made.m[11] = -1; + made.m[14] = near * far / (near - far); + return made; +} + +#! An orthographic projection of a box: its edges, and how near and far it +#! reaches down -z. +pub def mat4::orthographic(left: f32, right: f32, bottom: f32, top: f32, near: f32, far: f32): mat4 { + var made := mat4::identity; + made.m[0] = 2 / (right - left); + made.m[5] = 2 / (top - bottom); + made.m[10] = 1 / (near - far); + made.m[12] = -(right + left) / (right - left); + made.m[13] = -(top + bottom) / (top - bottom); + made.m[14] = near / (near - far); + return made; +} + +#! The view of a camera at a place looking at another, y as near to `up` as it +#! can be: what moves the world into the camera's space. +pub def mat4::look_at(eye: vec3, target: vec3, up: vec3 = vec3::up): mat4 { + return mat4::compose(eye, quat::looking(target - eye, up), vec3::one).inverse(); +} + +#! The matrix doing another, then this: each of the other's columns, each of +#! this one's columns scaled by one of its numbers, added. +pub def mat4::mul(&this, other: &mat4): mat4 { + var made := mat4{}; + if lanes_held() { + val c0 := lanes_of(&this.m[0]); + val c1 := lanes_of(&this.m[4]); + val c2 := lanes_of(&this.m[8]); + val c3 := lanes_of(&this.m[12]); + val out := (&mut made) as *mut f32x4; + for c in 0..4u { + out[c] = c0 * f32x4::splat(other.m[c * 4]) + c1 * f32x4::splat(other.m[c * 4 + 1]) + + c2 * f32x4::splat(other.m[c * 4 + 2]) + c3 * f32x4::splat(other.m[c * 4 + 3]); + } + return made; + } + for c in 0..4u { + for r in 0..4u { + made.m[c * 4 + r] = this.m[r] * other.m[c * 4] + this.m[4 + r] * other.m[c * 4 + 1] + + this.m[8 + r] * other.m[c * 4 + 2] + this.m[12 + r] * other.m[c * 4 + 3]; + } + } + return made; +} + +#! What the matrix makes of a vector, as a projection makes a place of clip +#! space: each column, scaled by one of its numbers, added. +pub def mat4::mul(&this, v: &vec4): vec4 { + if lanes_held() { + return of_lanes::(lanes_of(&this.m[0]) * f32x4::splat(v.x) + lanes_of(&this.m[4]) * f32x4::splat(v.y) + + lanes_of(&this.m[8]) * f32x4::splat(v.z) + lanes_of(&this.m[12]) * f32x4::splat(v.w)); + } + return vec4{ + this.m[0] * v.x + this.m[4] * v.y + this.m[8] * v.z + this.m[12] * v.w, + this.m[1] * v.x + this.m[5] * v.y + this.m[9] * v.z + this.m[13] * v.w, + this.m[2] * v.x + this.m[6] * v.y + this.m[10] * v.z + this.m[14] * v.w, + this.m[3] * v.x + this.m[7] * v.y + this.m[11] * v.z + this.m[15] * v.w, + }; +} + +pub def mat4::equals(&this, other: &mat4): bool { + for i in 0..16u { + return false if this.m[i] != other.m[i]; + } + return true; +} + +#! A place moved by the matrix, which moves, turns, and scales but doesn't +#! project. +pub def mat4::transform_point(&this, p: vec3): vec3 { + if lanes_held() { + return of_lanes::(lanes_of(&this.m[0]) * f32x4::splat(p.x) + lanes_of(&this.m[4]) * f32x4::splat(p.y) + + lanes_of(&this.m[8]) * f32x4::splat(p.z) + lanes_of(&this.m[12])); + } + return vec3{ + this.m[0] * p.x + this.m[4] * p.y + this.m[8] * p.z + this.m[12], + this.m[1] * p.x + this.m[5] * p.y + this.m[9] * p.z + this.m[13], + this.m[2] * p.x + this.m[6] * p.y + this.m[10] * p.z + this.m[14], + }; +} + +#! A direction turned and scaled by the matrix, which a move doesn't change. +pub def mat4::transform_vector(&this, v: vec3): vec3 { + if lanes_held() { + return of_lanes::(lanes_of(&this.m[0]) * f32x4::splat(v.x) + lanes_of(&this.m[4]) * f32x4::splat(v.y) + + lanes_of(&this.m[8]) * f32x4::splat(v.z)); + } + return vec3{ + this.m[0] * v.x + this.m[4] * v.y + this.m[8] * v.z, + this.m[1] * v.x + this.m[5] * v.y + this.m[9] * v.z, + this.m[2] * v.x + this.m[6] * v.y + this.m[10] * v.z, + }; +} + +#! Where the matrix moves the origin to. +pub val mat4::translation_of: vec3 { + get => vec3{ this.m[12], this.m[13], this.m[14] }; +} + +#! A column, from 0. +pub def mat4::column(&this, which: u64): vec4 { + return vec4{ this.m[which * 4], this.m[which * 4 + 1], this.m[which * 4 + 2], this.m[which * 4 + 3] }; +} + +#! What it does to directions: its first three columns' first three numbers. +pub def mat4::linear_part(&this): mat3 { + return mat3{ + vec3{ this.m[0], this.m[1], this.m[2] }, + vec3{ this.m[4], this.m[5], this.m[6] }, + vec3{ this.m[8], this.m[9], this.m[10] }, + }; +} + +pub def mat4::transposed(&this): mat4 { + var made := mat4{}; + for c in 0..4u { + for r in 0..4u { + made.m[c * 4 + r] = this.m[r * 4 + c]; + } + } + return made; +} + +#! The matrix undoing this, or none where nothing can, as a scale of zero: of +#! the determinants of two by two its first two columns make, and its last +#! two, each cofactor of three of them, which is half the work of the +#! cofactors written out, a number at a time. +pub def mat4::inverse(&this): mat4 { + val a := &this.m; + val s0 := a[0] * a[5] - a[4] * a[1]; + val s1 := a[0] * a[6] - a[4] * a[2]; + val s2 := a[0] * a[7] - a[4] * a[3]; + val s3 := a[1] * a[6] - a[5] * a[2]; + val s4 := a[1] * a[7] - a[5] * a[3]; + val s5 := a[2] * a[7] - a[6] * a[3]; + val c5 := a[10] * a[15] - a[14] * a[11]; + val c4 := a[9] * a[15] - a[13] * a[11]; + val c3 := a[9] * a[14] - a[13] * a[10]; + val c2 := a[8] * a[15] - a[12] * a[11]; + val c1 := a[8] * a[14] - a[12] * a[10]; + val c0 := a[8] * a[13] - a[12] * a[9]; + val det := s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0; + # Scaled by 0 where nothing undoes it, so it returns once. + val k := det != 0 ? 1 / det : 0; + return mat4{ m = [ + (a[5] * c5 - a[6] * c4 + a[7] * c3) * k, + (a[2] * c4 - a[1] * c5 - a[3] * c3) * k, + (a[13] * s5 - a[14] * s4 + a[15] * s3) * k, + (a[10] * s4 - a[9] * s5 - a[11] * s3) * k, + (a[6] * c2 - a[4] * c5 - a[7] * c1) * k, + (a[0] * c5 - a[2] * c2 + a[3] * c1) * k, + (a[14] * s2 - a[12] * s5 - a[15] * s1) * k, + (a[8] * s5 - a[10] * s2 + a[11] * s1) * k, + (a[4] * c4 - a[5] * c2 + a[7] * c0) * k, + (a[1] * c2 - a[0] * c4 - a[3] * c0) * k, + (a[12] * s4 - a[13] * s2 + a[15] * s0) * k, + (a[9] * s2 - a[8] * s4 - a[11] * s0) * k, + (a[5] * c1 - a[4] * c3 - a[6] * c0) * k, + (a[0] * c3 - a[1] * c1 + a[2] * c0) * k, + (a[13] * s1 - a[12] * s3 - a[14] * s0) * k, + (a[8] * s3 - a[9] * s1 + a[10] * s0) * k, + ] }; +} diff --git a/linear/quat.sakura b/linear/quat.sakura new file mode 100644 index 0000000..9899402 --- /dev/null +++ b/linear/quat.sakura @@ -0,0 +1,156 @@ +#! Contains `quat`, a rotation as a quaternion of length 1: made of an axis and +#! an angle, of angles about each axis, or of a direction to look in; turning +#! vectors, following one another, undone, and turned between at an even rate. + +import std::math; +import std::serial; +module malunal::linear; + +#! A rotation, as a quaternion of length 1. +@serial +pub struct quat { + @serial pub var x: f32; + @serial pub var y: f32; + @serial pub var z: f32; + @serial pub var w: f32 = 1; +} + +#! No rotation. +pub val quat::identity := quat{ 0, 0, 0, 1 }; + +#! Its numbers as lanes, for code of its own to work several at once. +pub def quat::lanes(&this): f32x4 { return lanes_of(this); } + +#! The quaternion of lanes. +pub def quat::of_lanes(lanes: f32x4): quat { return of_lanes::(lanes); } + +#! A rotation about an axis, by an angle, counterclockwise as the axis points +#! at the viewer. +pub def quat::axis_angle(axis: vec3, angle: f32): quat { + val a := axis.normalized(); + val s := math::sin(angle / 2); + return quat{ a.x * s, a.y * s, a.z * s, math::cos(angle / 2) }; +} + +#! A rotation by angles about each axis, as a camera's is: about z, its roll, +#! then about x, its pitch, then about y, its yaw. +pub def quat::euler(x: f32, y: f32, z: f32): quat { + return quat::axis_angle(vec3::up, y) * quat::axis_angle(vec3::right, x) * quat::axis_angle(vec3::back, z); +} + +#! The rotation turning -z, where a camera looks, to a direction, and y as near +#! to `up` as it can be. +pub def quat::looking(direction: vec3, up: vec3 = vec3::up): quat { + val f := direction.normalized(); + var r := f.cross(up).normalized(); + if r.length == 0 { + # Looking along `up`, any right will do. + r = f.cross(math::abs(f.x) < 0.9 ? vec3::right : vec3::up).normalized(); + } + val u := r.cross(f); + return quat::of_basis(r, u, -f); +} + +#! The shortest rotation turning one direction to another, each of length 1, +#! as what stands up along y is turned to stand along another way. +pub def quat::between(from: vec3, to: vec3): quat { + val d := from.dot(to); + if d < -0.999999 { + # Opposite ways: half a turn about any axis across them. + val across := from.cross(math::abs(from.x) < 0.9 ? vec3::right : vec3::up).normalized(); + return quat{ across.x, across.y, across.z, 0 }; + } + val c := from.cross(to); + return quat{ c.x, c.y, c.z, 1 + d }.normalized(); +} + +#! The rotation whose matrix's columns are three axes, at right angles, each of +#! length 1, as `mat3::rotation` gives them. +pub def quat::of_basis(x: vec3, y: vec3, z: vec3): quat { + val trace := x.x + y.y + z.z; + if trace > 0 { + val s := math::sqrt(trace + 1) * 2; + return quat{ (y.z - z.y) / s, (z.x - x.z) / s, (x.y - y.x) / s, s / 4 }; + } + if x.x > y.y && x.x > z.z { + val s := math::sqrt(1 + x.x - y.y - z.z) * 2; + return quat{ s / 4, (y.x + x.y) / s, (z.x + x.z) / s, (y.z - z.y) / s }; + } + if y.y > z.z { + val s := math::sqrt(1 + y.y - x.x - z.z) * 2; + return quat{ (y.x + x.y) / s, s / 4, (z.y + y.z) / s, (z.x - x.z) / s }; + } + val s := math::sqrt(1 + z.z - x.x - y.y) * 2; + return quat{ (z.x + x.z) / s, (z.y + y.z) / s, s / 4, (x.y - y.x) / s }; +} + +#! The rotation of this after another: `a * b` turns by `b`, then by `a`. A +#! number at a time, which an executable outruns gathering the other's numbers +#! into lanes with. +pub def quat::mul(&this, o: &quat): quat { + return quat{ + o.x * this.w + o.w * this.x + o.z * this.y - o.y * this.z, + o.y * this.w - o.z * this.x + o.w * this.y + o.x * this.z, + o.z * this.w + o.y * this.x - o.x * this.y + o.w * this.z, + o.w * this.w - o.x * this.x - o.y * this.y - o.z * this.z, + }; +} + +#! A vector turned by the rotation, by its matrix, whose columns are scaled by +#! the vector's numbers and added as lanes, which an executable works three +#! times as fast as the crosses of the rotation's axis. +pub def quat::mul(&this, v: &vec3): vec3 { + return mat3::rotation(this) * v; +} + +pub def quat::equals(&this, other: &quat): bool { + return this.x == other.x && this.y == other.y && this.z == other.z && this.w == other.w; +} + +pub def quat::dot(&this, other: quat): f32 { + if lanes_held() { + val p := lanes_of(this) * lanes_of(&other); + return p[0] + p[1] + p[2] + p[3]; + } + return this.x * other.x + this.y * other.y + this.z * other.z + this.w * other.w; +} + +pub val quat::length: f32 { + get => math::sqrt(this.dot(this)); +} + +#! The rotation back. +pub def quat::inverse(&this): quat { + return quat{ -this.x, -this.y, -this.z, this.w }; +} + +#! The quaternion at a length of 1, as rounding keeps a rotation turned many +#! times. +pub def quat::normalized(&this): quat { + val l := this.length; + if lanes_held() { + return l > 0 ? of_lanes::(lanes_of(this) / f32x4::splat(l)) : quat::identity; + } + return l > 0 ? quat{ this.x / l, this.y / l, this.z / l, this.w / l } : quat::identity; +} + +#! The rotation a fraction of the way to another, turning at an even rate by +#! the shorter way. +pub def quat::slerp(&this, to: quat, t: f32): quat { + var cos := this.dot(to); + var end := to; + if cos < 0 { + cos = -cos; + end = quat{ -to.x, -to.y, -to.z, -to.w }; + } + var a := 1 - t; + var b := t; + if cos < 0.9995 { + val angle := math::acos(cos); + val s := math::sin(angle); + a = math::sin((1 - t) * angle) / s; + b = math::sin(t * angle) / s; + } + val made := quat{ this.x * a + end.x * b, this.y * a + end.y * b, this.z * a + end.z * b, this.w * a + end.w * b }; + return made.normalized(); +} diff --git a/linear/vec2.sakura b/linear/vec2.sakura new file mode 100644 index 0000000..9d01b4a --- /dev/null +++ b/linear/vec2.sakura @@ -0,0 +1,66 @@ +#! Contains `vec2`, a vector of two: a place or a direction in a plane, as of +#! a window's pixels, a glyph's outline, or a texture. It's 8 bytes, half the +#! lanes of an `f32x4`, so it's worked a number at a time. + +import std::math; +import std::serial; +module malunal::linear; + +#! A vector of two: a place or a direction in a plane. +@serial +pub struct vec2 { + @serial pub var x: f32; + @serial pub var y: f32; +} + +pub val vec2::zero := vec2{ 0, 0 }; +pub val vec2::one := vec2{ 1, 1 }; + +pub def vec2::add(&this, other: &vec2): vec2 { return vec2{ this.x + other.x, this.y + other.y }; } +pub def vec2::sub(&this, other: &vec2): vec2 { return vec2{ this.x - other.x, this.y - other.y }; } +pub def vec2::mul(&this, by: &f32): vec2 { return vec2{ this.x * by, this.y * by }; } +pub def vec2::mul(&this, other: &vec2): vec2 { return vec2{ this.x * other.x, this.y * other.y }; } +pub def vec2::div(&this, by: &f32): vec2 { return vec2{ this.x / by, this.y / by }; } +pub def vec2::div(&this, other: &vec2): vec2 { return vec2{ this.x / other.x, this.y / other.y }; } +pub def vec2::negate(&this): vec2 { return vec2{ -this.x, -this.y }; } +pub def vec2::equals(&this, other: &vec2): bool { return this.x == other.x && this.y == other.y; } + +pub def vec2::dot(&this, other: vec2): f32 { return this.x * other.x + this.y * other.y; } + +#! The z of the cross product of the two as vectors of three in the plane z is +#! 0: positive where `other` is counterclockwise of this. +pub def vec2::cross(&this, other: vec2): f32 { return this.x * other.y - this.y * other.x; } + +#! The vector turned a quarter counterclockwise. +pub def vec2::perpendicular(&this): vec2 { return vec2{ -this.y, this.x }; } + +pub val vec2::length: f32 { + get => math::sqrt(this.x * this.x + this.y * this.y); +} + +#! The length squared, which needs no square root, to compare lengths by. +pub val vec2::length_squared: f32 { + get => this.x * this.x + this.y * this.y; +} + +pub def vec2::distance(&this, other: vec2): f32 { return (other - this).length; } + +#! The vector at a length of 1, or none where it has no length. +pub def vec2::normalized(&this): vec2 { + val l := math::sqrt(this.x * this.x + this.y * this.y); + return l > 0 ? vec2{ this.x / l, this.y / l } : vec2{}; +} + +#! The vector a fraction of the way to another. +pub def vec2::lerp(&this, to: vec2, t: f32): vec2 { + return vec2{ this.x + (to.x - this.x) * t, this.y + (to.y - this.y) * t }; +} + +#! The lesser of each pair of numbers, as `math::min` gives it. +pub def vec2::min(&this, other: vec2): vec2 { return vec2{ math::min(this.x, other.x), math::min(this.y, other.y) }; } + +#! The greater of each pair of numbers, as `math::max` gives it. +pub def vec2::max(&this, other: vec2): vec2 { return vec2{ math::max(this.x, other.x), math::max(this.y, other.y) }; } + +#! Each number's distance from zero. +pub def vec2::abs(&this): vec2 { return vec2{ math::abs(this.x), math::abs(this.y) }; } diff --git a/linear/vec3.sakura b/linear/vec3.sakura new file mode 100644 index 0000000..f887cf3 --- /dev/null +++ b/linear/vec3.sakura @@ -0,0 +1,138 @@ +#! Contains `vec3`, a vector of three: a place or a direction in space. It holds +#! a fourth number no one names, so it's 16 bytes, an `f32x4`'s, which an +#! executable holding vectors in registers works at once. + +import std::math; +import std::serial; +module malunal::linear; + +#! A vector of three: a place or a direction in space. +@serial +pub struct vec3 { + @serial pub var x: f32; + @serial pub var y: f32; + @serial pub var z: f32; + # Unnamed, so the vector is four lanes; what its lane holds means nothing. + var _w: f32; +} + +pub val vec3::zero := vec3{ 0, 0, 0 }; +pub val vec3::one := vec3{ 1, 1, 1 }; +pub val vec3::right := vec3{ 1, 0, 0 }; +pub val vec3::left := vec3{ -1, 0, 0 }; +pub val vec3::up := vec3{ 0, 1, 0 }; +pub val vec3::down := vec3{ 0, -1, 0 }; +#! Toward the viewer: a camera looks the other way. +pub val vec3::back := vec3{ 0, 0, 1 }; +#! Away from the viewer, where a camera looks. +pub val vec3::forward := vec3{ 0, 0, -1 }; + +#! Its numbers as lanes, the fourth meaning nothing, for code of its own to +#! work several at once. +pub def vec3::lanes(&this): f32x4 { return lanes_of(this); } + +#! The vector of the first three of lanes. +pub def vec3::of_lanes(lanes: f32x4): vec3 { return of_lanes::(lanes); } + +pub def vec3::add(&this, other: &vec3): vec3 { + return of_lanes::(lanes_of(this) + lanes_of(other)) if lanes_held(); + return vec3{ this.x + other.x, this.y + other.y, this.z + other.z }; +} + +pub def vec3::sub(&this, other: &vec3): vec3 { + return of_lanes::(lanes_of(this) - lanes_of(other)) if lanes_held(); + return vec3{ this.x - other.x, this.y - other.y, this.z - other.z }; +} + +pub def vec3::mul(&this, by: &f32): vec3 { + return of_lanes::(lanes_of(this) * f32x4::splat(by)) if lanes_held(); + return vec3{ this.x * by, this.y * by, this.z * by }; +} + +pub def vec3::mul(&this, other: &vec3): vec3 { + return of_lanes::(lanes_of(this) * lanes_of(other)) if lanes_held(); + return vec3{ this.x * other.x, this.y * other.y, this.z * other.z }; +} + +pub def vec3::div(&this, by: &f32): vec3 { + return of_lanes::(lanes_of(this) / f32x4::splat(by)) if lanes_held(); + return vec3{ this.x / by, this.y / by, this.z / by }; +} + +pub def vec3::div(&this, other: &vec3): vec3 { + if lanes_held() { + # The unnamed lanes divide 0 by 0, which is kept from the vector. + var made := of_lanes::(lanes_of(this) / lanes_of(other)); + made._w = 0; + return made; + } + return vec3{ this.x / other.x, this.y / other.y, this.z / other.z }; +} + +pub def vec3::negate(&this): vec3 { + return of_lanes::(-lanes_of(this)) if lanes_held(); + return vec3{ -this.x, -this.y, -this.z }; +} + +pub def vec3::equals(&this, other: &vec3): bool { + return this.x == other.x && this.y == other.y && this.z == other.z; +} + +pub def vec3::dot(&this, other: vec3): f32 { + if lanes_held() { + val p := lanes_of(this) * lanes_of(&other); + return p[0] + p[1] + p[2]; + } + return this.x * other.x + this.y * other.y + this.z * other.z; +} + +#! The vector at right angles to both, by the right hand: x cross y is z. Its +#! lanes would be shuffled, which no instruction does, so it's a number at a +#! time. +pub def vec3::cross(&this, other: vec3): vec3 { + return vec3{ + this.y * other.z - this.z * other.y, + this.z * other.x - this.x * other.z, + this.x * other.y - this.y * other.x, + }; +} + +pub val vec3::length: f32 { + get => math::sqrt(this.dot(this)); +} + +#! The length squared, which needs no square root, to compare lengths by. +pub val vec3::length_squared: f32 { + get => this.dot(this); +} + +pub def vec3::distance(&this, other: vec3): f32 { return (other - this).length; } + +#! The vector at a length of 1, or none where it has no length. +pub def vec3::normalized(&this): vec3 { + val l := this.length; + return l > 0 ? this / l : vec3{}; +} + +#! The vector a fraction of the way to another. +pub def vec3::lerp(&this, to: vec3, t: f32): vec3 { + return this + (to - this) * t; +} + +#! The lesser of each pair of numbers, as `math::min` gives it. +pub def vec3::min(&this, other: vec3): vec3 { + return of_lanes::(lanes_of(this).min(&lanes_of(&other))) if lanes_held(); + return vec3{ math::min(this.x, other.x), math::min(this.y, other.y), math::min(this.z, other.z) }; +} + +#! The greater of each pair of numbers, as `math::max` gives it. +pub def vec3::max(&this, other: vec3): vec3 { + return of_lanes::(lanes_of(this).max(&lanes_of(&other))) if lanes_held(); + return vec3{ math::max(this.x, other.x), math::max(this.y, other.y), math::max(this.z, other.z) }; +} + +#! Each number's distance from zero. +pub def vec3::abs(&this): vec3 { + return of_lanes::(lanes_of(this).abs()) if lanes_held(); + return vec3{ math::abs(this.x), math::abs(this.y), math::abs(this.z) }; +} diff --git a/linear/vec4.sakura b/linear/vec4.sakura new file mode 100644 index 0000000..4328eb5 --- /dev/null +++ b/linear/vec4.sakura @@ -0,0 +1,116 @@ +#! Contains `vec4`, a vector of four: a place of space with its `w`, as a +#! matrix projects one, or four numbers worked alike, as a color's. It's an +#! `f32x4`'s 16 bytes, which an executable holding vectors in registers works at +#! once. + +import std::math; +import std::serial; +module malunal::linear; + +#! A vector of four, as a point of space with its `w`. +@serial +pub struct vec4 { + @serial pub var x: f32; + @serial pub var y: f32; + @serial pub var z: f32; + @serial pub var w: f32; +} + +pub val vec4::zero := vec4{ 0, 0, 0, 0 }; +pub val vec4::one := vec4{ 1, 1, 1, 1 }; + +#! Its numbers as lanes, for code of its own to work several at once. +pub def vec4::lanes(&this): f32x4 { return lanes_of(this); } + +#! The vector of lanes. +pub def vec4::of_lanes(lanes: f32x4): vec4 { return of_lanes::(lanes); } + +pub def vec4::add(&this, other: &vec4): vec4 { + return of_lanes::(lanes_of(this) + lanes_of(other)) if lanes_held(); + return vec4{ this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w }; +} + +pub def vec4::sub(&this, other: &vec4): vec4 { + return of_lanes::(lanes_of(this) - lanes_of(other)) if lanes_held(); + return vec4{ this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w }; +} + +pub def vec4::mul(&this, by: &f32): vec4 { + return of_lanes::(lanes_of(this) * f32x4::splat(by)) if lanes_held(); + return vec4{ this.x * by, this.y * by, this.z * by, this.w * by }; +} + +pub def vec4::mul(&this, other: &vec4): vec4 { + return of_lanes::(lanes_of(this) * lanes_of(other)) if lanes_held(); + return vec4{ this.x * other.x, this.y * other.y, this.z * other.z, this.w * other.w }; +} + +pub def vec4::div(&this, by: &f32): vec4 { + return of_lanes::(lanes_of(this) / f32x4::splat(by)) if lanes_held(); + return vec4{ this.x / by, this.y / by, this.z / by, this.w / by }; +} + +pub def vec4::div(&this, other: &vec4): vec4 { + return of_lanes::(lanes_of(this) / lanes_of(other)) if lanes_held(); + return vec4{ this.x / other.x, this.y / other.y, this.z / other.z, this.w / other.w }; +} + +pub def vec4::negate(&this): vec4 { + return of_lanes::(-lanes_of(this)) if lanes_held(); + return vec4{ -this.x, -this.y, -this.z, -this.w }; +} + +pub def vec4::equals(&this, other: &vec4): bool { + return this.x == other.x && this.y == other.y && this.z == other.z && this.w == other.w; +} + +pub def vec4::dot(&this, other: vec4): f32 { + if lanes_held() { + val p := lanes_of(this) * lanes_of(&other); + return p[0] + p[1] + p[2] + p[3]; + } + return this.x * other.x + this.y * other.y + this.z * other.z + this.w * other.w; +} + +pub val vec4::length: f32 { + get => math::sqrt(this.dot(this)); +} + +#! The length squared, which needs no square root, to compare lengths by. +pub val vec4::length_squared: f32 { + get => this.dot(this); +} + +#! The vector at a length of 1, or none where it has no length. +pub def vec4::normalized(&this): vec4 { + val l := this.length; + return l > 0 ? this / l : vec4{}; +} + +#! The vector a fraction of the way to another. +pub def vec4::lerp(&this, to: vec4, t: f32): vec4 { + return this + (to - this) * t; +} + +#! The lesser of each pair of numbers, as `math::min` gives it. +pub def vec4::min(&this, other: vec4): vec4 { + return of_lanes::(lanes_of(this).min(&lanes_of(&other))) if lanes_held(); + return vec4{ math::min(this.x, other.x), math::min(this.y, other.y), math::min(this.z, other.z), math::min(this.w, other.w) }; +} + +#! The greater of each pair of numbers, as `math::max` gives it. +pub def vec4::max(&this, other: vec4): vec4 { + return of_lanes::(lanes_of(this).max(&lanes_of(&other))) if lanes_held(); + return vec4{ math::max(this.x, other.x), math::max(this.y, other.y), math::max(this.z, other.z), math::max(this.w, other.w) }; +} + +#! Each number's distance from zero. +pub def vec4::abs(&this): vec4 { + return of_lanes::(lanes_of(this).abs()) if lanes_held(); + return vec4{ math::abs(this.x), math::abs(this.y), math::abs(this.z), math::abs(this.w) }; +} + +#! Its first three. +pub val vec4::xyz: vec3 { + get => vec3{ this.x, this.y, this.z }; +} diff --git a/photometry/exposure.sakura b/photometry/exposure.sakura new file mode 100644 index 0000000..81aa11d --- /dev/null +++ b/photometry/exposure.sakura @@ -0,0 +1,46 @@ +#! Contains exposure: how a camera is set for a scene's light, as an exposure +#! value at ISO 100, of its settings or of what its meter reads; and what light +#! is multiplied by, so exposed, as a renderer records it. +#! +#! Exposed by a meter, a matte white surface lit as the meter read records as +#! about two thirds of the most, and an 18% grey card about an eighth, which an +#! sRGB display shows as middle grey. + +import std::math; +module malunal::photometry; + +#! The exposure value at ISO 100 of a camera's settings: its aperture's +#! f-number, its shutter's time open, in seconds, and its sensitivity, as ISO. +#! It's log₂(N²/t), a step less each time the ISO doubles past 100, so f/16 at a +#! hundredth of a second is about 15, a sunny day's, as the sunny 16 rule has +#! it. +pub def ev100_of_camera(aperture: f32, shutter: f32, iso: f32 = 100): f32 { + return math::log2(aperture * aperture / shutter) - math::log2(iso / 100); +} + +#! The exposure value at ISO 100 a camera's own meter sets for a scene of an +#! average luminance, in nits, calibrated as such meters are, by 12.5: +#! log₂(nits × 100 / 12.5). +pub def ev100_of_nits(luminance: f32): f32 { + return math::log2(luminance * 8); +} + +#! The exposure value at ISO 100 a meter held where a scene is lit sets for it, +#! of the lux it reads, calibrated as such meters are, by 250: +#! log₂(lux × 100 / 250). Direct sunlight's is about 15.3, an office's 7.3. +pub def ev100_of_lux(illuminance: f32): f32 { + return math::log2(illuminance * 0.4); +} + +#! What light, in nits, is multiplied by, recorded by a camera at an exposure +#! value at ISO 100: the most it records, 1, over the luminance that fills its +#! sensor, 1.2 × 2^EV100 nits. +pub def exposure_of_ev100(ev100: f32): f32 { + return 1 / (1.2 * math::exp2(ev100)); +} + +#! The exposure value at ISO 100 at which light is multiplied by so much, as +#! `exposure_of_ev100` gives it. +pub def ev100_of_exposure(exposure: f32): f32 { + return -math::log2(1.2 * exposure); +} diff --git a/photometry/photometry.sakura b/photometry/photometry.sakura new file mode 100644 index 0000000..14ba22a --- /dev/null +++ b/photometry/photometry.sakura @@ -0,0 +1,157 @@ +#! Contains `photometry`: light as an eye sees it, in the units lights are named +#! by, and converted between them, so a game's lights are given as real ones +#! are: a bulb by its lumens, the sun by the lux it lights the ground with, the +#! sky by its luminance, and a camera by its exposure value. +#! +#! ``` +#! lumens lm luminous flux: all the light a source gives, every way at once, as a bulb is sold by +#! candela cd, lm/sr luminous intensity: the light a source gives one way, in each steradian of it +#! lux lx, lm/m² illuminance: the light falling on a surface, as a meter on it reads +#! nits cd/m² luminance: the light a surface gives back toward an eye, or a sky gives +#! EV100 exposure value at ISO 100: how a camera is set for a scene's light, each step twice the light +#! ``` +#! +#! Angles are radians, and a cone's angle is its half, from its axis to its +#! edge, as glTF's spot lights give theirs. + +import std::math; +module malunal::photometry; + +# π, as the `f32` nearest it. +const pi: f32 = 3.14159265; + +#! The solid angle of a cone, in steradians: 2π(1 - cos angle), of its angle +#! from its axis to its edge. Of π, it's a sphere's, 4π. +pub def solid_angle_of(angle: f32): f32 { + return 2 * pi * (1 - math::cos(angle)); +} + +#! The candela of a light giving so many lumens within a cone, alike every way +#! within it: its lumens over the cone's solid angle. Of the angle left out, π, +#! it shines every way, as a bare bulb does, so it's its lumens over 4π; of a +#! narrower cone, its light is gathered into it, as a torch's reflector gathers +#! its bulb's, and it's brighter each way. +pub def candela_of_lumens(flux: f32, angle: f32 = pi): f32 { + return flux / solid_angle_of(angle); +} + +#! The lumens of a light of so many candela within a cone, alike every way +#! within it, or every way, of the angle left out. +pub def lumens_of_candela(intensity: f32, angle: f32 = pi): f32 { + return intensity * solid_angle_of(angle); +} + +#! The lumens of a lamp drawing so many watts, of how many lumens each watt of +#! its kind gives, as `efficacy` names them. +pub def lumens_of_watts(power: f32, lumens_per_watt: f32): f32 { + return power * lumens_per_watt; +} + +#! The watts a lamp of so many lumens draws, of how many lumens each watt of +#! its kind gives. +pub def watts_of_lumens(flux: f32, lumens_per_watt: f32): f32 { + return flux / lumens_per_watt; +} + +#! The lux a light of so many candela gives a surface so far from it, facing +#! it: its candela over the square of the distance. A surface turned from it is +#! given the cosine of the angle as much. +pub def lux_of_candela(intensity: f32, distance: f32): f32 { + return intensity / (distance * distance); +} + +#! How far from a light of so many candela a surface facing it is given so many +#! lux: the square root of its candela over them, as far as it lights as much +#! as is seen. +pub def distance_of_lux(intensity: f32, illuminance: f32): f32 { + return math::sqrt(intensity / illuminance); +} + +#! The nits a matte surface lit by so many lux gives back, every way alike, of +#! the fraction of what falls on it it gives back: what falls on it, by that +#! fraction, over π. White gives back all of it, and an 18% grey card, a +#! photograph's middle grey, 0.18. +pub def nits_of_lux(illuminance: f32, reflectance: f32 = 1): f32 { + return illuminance * reflectance / pi; +} + +#! The lux lighting a matte surface that gives back so many nits, of the +#! fraction of what falls on it it gives back: π times its nits, over that +#! fraction. Of the fraction left out, it's the lux a sky of so many nits, alike +#! every way, lights the ground with. +pub def lux_of_nits(luminance: f32, reflectance: f32 = 1): f32 { + return luminance * pi / reflectance; +} + +#! Illuminances, in lux, of the ground or a floor, about as each is lit. +pub struct lux {} + +#! A moonless, overcast night, lit by starlight. +pub const lux::starlight: f32 = 0.0001; +#! A moonless clear night, lit by the sky's own glow. +pub const lux::moonless_night: f32 = 0.002; +#! A full moon on a clear night. +pub const lux::full_moon: f32 = 0.2; +#! The end of civil twilight, under a clear sky. +pub const lux::twilight: f32 = 3.4; +#! A family's living room. +pub const lux::living_room: f32 = 50; +#! An office building's hallway. +pub const lux::hallway: f32 = 80; +#! A very dark overcast day. +pub const lux::dark_overcast: f32 = 100; +#! An office's desks. +pub const lux::office: f32 = 400; +#! Sunrise or sunset on a clear day. +pub const lux::sunrise: f32 = 400; +#! An overcast day. +pub const lux::overcast: f32 = 1000; +#! Full daylight, out of the sun. +pub const lux::daylight: f32 = 20000; +#! Direct sunlight, at noon. +pub const lux::direct_sunlight: f32 = 100000; + +#! Luminances, in nits, about as each is seen. +pub struct nits {} + +#! The sky of a clear day, out of the sun, which lights the ground with about +#! 22,000 lux. +pub const nits::clear_sky: f32 = 7000; + +#! Luminous fluxes, in lumens, about as each is sold or burns. +pub struct lumens {} + +#! A candle, of a candela every way. +pub const lumens::candle: f32 = 12.566371; +#! A bulb as bright as a 40-watt incandescent bulb, as LED bulbs are sold. +pub const lumens::bulb_40w: f32 = 450; +#! As bright as a 60-watt incandescent bulb. +pub const lumens::bulb_60w: f32 = 800; +#! As bright as a 75-watt incandescent bulb. +pub const lumens::bulb_75w: f32 = 1100; +#! As bright as a 100-watt incandescent bulb. +pub const lumens::bulb_100w: f32 = 1600; + +#! Luminous intensities, in candela. +pub struct candela {} + +#! A candle's, every way, which the candela was first named for. +pub const candela::candle: f32 = 1; + +#! How many lumens each watt a lamp draws gives, by its kind, about, as +#! `lumens_of_watts` takes them. +pub struct efficacy {} + +#! The most a watt gives, as green light of 555 nm, by which the lumen is +#! defined. +pub const efficacy::most: f32 = 683; +#! An incandescent bulb's. +pub const efficacy::incandescent: f32 = 14; +#! A halogen bulb's. +pub const efficacy::halogen: f32 = 20; +#! A compact fluorescent bulb's. +pub const efficacy::fluorescent: f32 = 60; +#! A white LED's. +pub const efficacy::led: f32 = 100; +#! Sunlight's, of each watt of it falling on the ground. +pub const efficacy::sunlight: f32 = 93; diff --git a/photometry/temperature.sakura b/photometry/temperature.sakura new file mode 100644 index 0000000..7a12644 --- /dev/null +++ b/photometry/temperature.sakura @@ -0,0 +1,34 @@ +#! Contains color temperature: the color of a black body's light at a +#! temperature, as lamps' colors are named. + +import std::math; +import malunal::linear; +module malunal::photometry; + +#! The color of a black body's light at a temperature, in kelvin, as a lamp's +#! is named: a candle's about 1,900 K, a warm bulb's 2,700, daylight's 6,500, +#! and a blue sky's 10,000 and more. It's linear sRGB, its greatest channel 1, +#! as a light's color is, by its intensity. A temperature below 1,000 K, or past +#! 40,000, is taken as either. +#! +#! The color is of Krystek's fit of the Planckian locus, within a thousandth of +#! it from 1,000 K to 15,000, made sRGB of CIE 1931's XYZ, a channel past sRGB's +#! colors taken as none. +pub def color_of_temperature(kelvin: f32): vec3 { + val t := math::clamp(kelvin, 1000f, 40000f); + val tt := t * t; + # Where it lies in CIE 1960's u and v, then in 1931's x and y. + val u := (0.860117757 + 1.54118254e-4 * t + 1.28641212e-7 * tt) / (1 + 8.42420235e-4 * t + 7.08145163e-7 * tt); + val v := (0.317398726 + 4.22806245e-5 * t + 4.20481691e-8 * tt) / (1 - 2.89741816e-5 * t + 1.61456053e-7 * tt); + val d := 2 * u - 8 * v + 4; + val x := 3 * u / d; + val y := 2 * v / d; + # Of a brightness of 1. + val big_x := x / y; + val big_z := (1 - x - y) / y; + val r := math::max(3.2404542 * big_x - 1.5371385 - 0.4985314 * big_z, 0f); + val g := math::max(-0.9692660 * big_x + 1.8760108 + 0.0415560 * big_z, 0f); + val b := math::max(0.0556434 * big_x - 0.2040259 + 1.0572252 * big_z, 0f); + val most := math::max(r, math::max(g, b)); + return vec3{ r / most, g / most, b / most }; +} diff --git a/physics2d/aabb.sakura b/physics2d/aabb.sakura new file mode 100644 index 0000000..7e4bbce --- /dev/null +++ b/physics2d/aabb.sakura @@ -0,0 +1,94 @@ +#! Contains `aabb`, a box along the plane's axes, as what holds a shape, and +#! what an `aabb_tree` sorts. + +import std::math; +import std::serial; +import malunal::linear; +module malunal::physics2d; + +#! A box along the plane's axes, from its least corner to its greatest. +@serial +pub struct aabb { + @serial pub var min: vec2; + @serial pub var max: vec2; +} + +#! The box of a middle, reaching so far each way. +pub def aabb::around(center: vec2, half: vec2): aabb { + return aabb{ center - half, center + half }; +} + +pub def aabb::equals(&this, other: &aabb): bool { + return this.min == other.min && this.max == other.max; +} + +pub val aabb::center: vec2 { + get => (this.min + this.max) * 0.5; +} + +#! How far it reaches each way from its middle. +pub val aabb::half_size: vec2 { + get => (this.max - this.min) * 0.5; +} + +pub val aabb::size: vec2 { + get => this.max - this.min; +} + +#! How far around it is, which an `aabb_tree` weighs where to put a box by. +pub val aabb::perimeter: f32 { + get => 2 * ((this.max.x - this.min.x) + (this.max.y - this.min.y)); +} + +#! Whether a place is within it, its edges among it. +pub def aabb::contains(&this, p: vec2): bool { + return p.x >= this.min.x && p.x <= this.max.x && p.y >= this.min.y && p.y <= this.max.y; +} + +#! Whether it holds another box whole. +pub def aabb::encloses(&this, other: aabb): bool { + return other.min.x >= this.min.x && other.min.y >= this.min.y && other.max.x <= this.max.x && other.max.y <= this.max.y; +} + +#! Whether it and another box meet, touching among it. +pub def aabb::overlaps(&this, other: aabb): bool { + return other.min.x <= this.max.x && other.max.x >= this.min.x && other.min.y <= this.max.y && other.max.y >= this.min.y; +} + +#! The least box holding it and another. +pub def aabb::merged(&this, other: aabb): aabb { + return aabb{ this.min.min(other.min), this.max.max(other.max) }; +} + +#! It grown so far each way. +pub def aabb::grown(&this, by: f32): aabb { + return aabb{ this.min - vec2{ by, by }, this.max + vec2{ by, by } }; +} + +#! How far along a ray it's first met, from a place, along a direction, as far +#! as `reach` lengths of the direction: 0 where the place is within it. +pub def aabb::ray_hit(&this, origin: vec2, direction: vec2, reach: f32): maybe { + var low: f32 = 0; + var high := reach; + val origins: f32[2] = [origin.x, origin.y]; + val ways: f32[2] = [direction.x, direction.y]; + val lows: f32[2] = [this.min.x, this.min.y]; + val highs: f32[2] = [this.max.x, this.max.y]; + for i in 0..2u { + if math::abs(ways[i]) < tiny { + return nothing{} if origins[i] < lows[i] || origins[i] > highs[i]; + continue; + } + var near := (lows[i] - origins[i]) / ways[i]; + var far := (highs[i] - origins[i]) / ways[i]; + if near > far { + val swapped := near; + near = far; + far = swapped; + } + low = math::max(low, near); + high = math::min(high, far); + return nothing{} if low > high; + } + return low; +} diff --git a/physics2d/body.sakura b/physics2d/body.sakura new file mode 100644 index 0000000..c76030d --- /dev/null +++ b/physics2d/body.sakura @@ -0,0 +1,155 @@ +#! Contains `body` and `collider`, what a `space` is given to make a body and +#! the shapes it's of, and `body_id` and `collider_id`, which name them there. + +import malunal::linear; +module malunal::physics2d; + +#! What moves a body. +pub enum body_kind: u8 { + #! Nothing: it stays where it's put, as the ground does. + static, + #! Its velocity alone, as it's set: what it meets doesn't push it, as a + #! moving platform's doesn't. + kinematic, + #! Forces, gravity, and what it meets, as a crate. + dynamic, +} + +#! What a body is made as: its kind, its pose, how fast it moves at first, +#! and how it's slowed and pulled. +pub struct body { + pub var kind := body_kind::dynamic; + #! Where its origin is, and which way it's turned; its colliders' shapes are + #! of places about the origin. + pub var at := pose::identity; + #! How fast its center of mass moves, in lengths a second. + pub var velocity: vec2; + #! How fast it turns, in radians a second, counterclockwise. + pub var spin: f32; + #! How much of its velocity, and of its spin, it loses each second, as air + #! slows it. + pub var linear_damping: f32; + pub var angular_damping: f32; + #! How much of the space's gravity, and its own, pulls it: 0 floats. + pub var gravity_scale: f32 = 1; + #! A gravity of its own, added to the space's, as a planet's pulls what's + #! near it toward its middle. + pub var gravity: vec2; + #! Whether it never turns, as a character standing up doesn't. + pub var fixed_rotation: bool; + #! Whether it may sleep when it and what it rests on are still. + pub var can_sleep: bool = true; + #! Whether it's swept against moving bodies too, not only what stands + #! still, so it passes through nothing however fast it goes, as a shot. + pub var bullet: bool; + #! A number of its user's, as an entity's bits. + pub var data: u64; +} + +#! What a body's collider is made as: its shape, about the body's origin; its +#! density, which sums to the body's mass; how it slides and bounces; and the +#! layers it's on and meets. A collider of a grid, which `space::attach_grid` +#! gives a body, has no shape or density of its own. +pub struct collider { + pub var shape: shape; + #! Its mass for each area of 1. + pub var density: f32 = 1; + #! How hard it is to slide along: 0 slides freely. Two colliders' are mixed + #! as the square root of their product. + pub var friction: f32 = 0.6; + #! How much of its speed toward what it meets it keeps, bounced back: 0 + #! stops, 1 bounces as high as it fell. Two colliders' greater is taken. + pub var restitution: f32; + #! The layers it's on, and those it meets: two colliders meet where each is + #! on a layer of the other's mask. + pub var layers: u32 = 1; + pub var mask: u32 = 0xFFFFFFFF; + #! Whether it only notes what it overlaps, pushing nothing. + pub var sensor: bool; + #! Whether it's solid only to what comes onto it from the side `up` faces, + #! of its body's own directions, as a platform jumped through from below. + pub var one_way: bool; + pub var up := vec2{ 0, 1 }; + #! A number of its user's, as an entity's bits. + pub var data: u64; +} + +#! A body of a space, as `space::add` names it. +pub struct body_id { + pub var index: u32 = 0xFFFFFFFF; + pub var generation: u32; +} + +pub def body_id::equals(&this, other: &body_id): bool { + return this.index == other.index && this.generation == other.generation; +} + +#! A collider of a body of a space, as `space::attach` names it. +pub struct collider_id { + pub var index: u32 = 0xFFFFFFFF; + pub var generation: u32; +} + +pub def collider_id::equals(&this, other: &collider_id): bool { + return this.index == other.index && this.generation == other.generation; +} + +# No body, collider, contact, or joint. +const none: u32 = 0xFFFFFFFF; + +# A body as the space keeps it. +struct body_record { + var kind: body_kind; + var generation: u32; + var alive: bool; + var at: pose; # Of its origin. + var center: vec2; # Its center of mass, in the plane. + var local_center: vec2; # The same, of its own places. + var velocity: vec2; + var spin: f32; + var force: vec2; + var torque: f32; + var mass: f32; + var inv_mass: f32; + var inertia: f32; # About its center of mass. + var inv_inertia: f32; + var linear_damping: f32; + var angular_damping: f32; + var gravity_scale: f32 = 1; + var gravity: vec2; # Its own, added to the space's. + var fixed_rotation: bool; + var can_sleep: bool = true; + var awake: bool = true; + var sleep_time: f32; + var extent: f32; # How far its colliders reach from its center. + var least: f32; # How far its narrowest shape reaches from its middle. + var bullet: bool; + var colliders: u32 = 0xFFFFFFFF; + var joints: u32 = 0xFFFFFFFF; # Its first joint edge. + var group: u32 = 0xFFFFFFFF; # The first body of the group it sleeps with. + var next_in_group: u32 = 0xFFFFFFFF; + var slot: u32; # Its solver state this step, 0 where it doesn't move. + var data: u64; +} + +# A collider as the space keeps it: of a shape, or of a grid the space holds. +struct collider_record { + var made: collider; + var grid: u32 = 0xFFFFFFFF; + var body: u32; + var leaf: u32 = 0xFFFFFFFF; # Its leaf of the space's tree. + var next: u32 = 0xFFFFFFFF; # The body's next collider. + var generation: u32; + var alive: bool; + var moved: bool; # Whether it's to find what it newly nears. +} + +# Whether a body's kind is moved by what it meets. +def body_record::is_dynamic(&this): bool { + return this.kind == body_kind::dynamic; +} + +# Whether a collider is of a grid. +def collider_record::is_grid(&this): bool { + return this.grid != none; +} diff --git a/physics2d/chains.sakura b/physics2d/chains.sakura new file mode 100644 index 0000000..2e9c382 --- /dev/null +++ b/physics2d/chains.sakura @@ -0,0 +1,121 @@ +#! Contains chains of segments, as a level's ground and a cave's walls are +#! drawn, and one-way platforms, as a game jumps through from below. +#! +#! A chain's segments are each a collider of their own, met only on the side +#! their normals face, to the right going along the chain, as a polygon's +#! counterclockwise edges face out: what's behind a segment passes through it. +#! Where two segments join flat or hollow, neither pushes by the corner they +#! share, only by their faces, so a body slides across the joints as along one +#! surface, never caught on them, as Box2D's chains keep it; where they join at +#! a corner sticking out, the segment after it pushes by the corner, as far +#! around it as its face and the one before turn. +#! +#! A one-way collider is solid only to what comes onto it from the side its +#! `up` faces: a contact beginning from below it, or beside it, passes through +#! until the two part, as a platform is jumped through and landed on. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics2d; + +#! Gives a body a chain of segments through places, as a level's ground or a +#! cave's walls: each a collider of the chain's own, met on its side to the +#! right going from one place to the next, so ground runs right to left, and a +#! cave's walls, met from within, clockwise; `looped` joins the last place to +#! the first. Their density is passed over, so a chain weighs nothing. +pub def space::attach_chain(&mut this, to: body_id, places: span, looped: bool, made: collider): vector { + var ids := vector::::new(); + val n := places.length; + return ids if n < 2 || !this.has(to); + val segments := looped ? n : n - 1; + for i in 0..segments { + var before: maybe = nothing{}; + var after: maybe = nothing{}; + if looped || i > 0 { + before = places[(i + n - 1) % n]; + } + if looped || i + 2 < n { + after = places[(i + 2) % n]; + } + var piece := made; + piece.shape = shape::chain_segment(places[i], places[(i + 1) % n], before, after); + piece.density = 0; + ids.append(this.attach(to, piece)); + } + return ids; +} + +# The middle of a shape's points, of its own places. +def shape::middle(&this): vec2 { + var sum := vec2::zero; + for i in 0..this._count { + sum = sum + this._points[i]; + } + return sum * (1 / this._count as f32); +} + +# A manifold of a chain's segment against another shape, met only on the +# segment's front, and by its ends only where they're the chain's own, or a +# corner sticking out the segment begins at: nothing where it's met otherwise, +# as the segment beside it meets it by its face. +def chained(segment: &shape, at: pose, other: &shape, at_other: pose, m: manifold): manifold { + return m if m.count == 0; + val p1 := at.apply(segment._points[0]); + val p2 := at.apply(segment._points[1]); + val n := at.turn.apply(segment._normals[0]); + return manifold{} if n.dot(at_other.apply(other.middle()) - p1) < 0; + return m if m.normal.dot(n) >= 0.9999; + val along := p2 - p1; + var spot := vec2::zero; + for i in 0..m.count { + spot = spot + m.points[i].point; + } + spot = spot * (1 / m.count as f32); + if (spot - p1).dot(along) >= 0.5 * along.length_squared { + # Its end: the segment after it meets what's there. + return manifold{} if (segment._chained & 4) != 0; + return m; + } + return m if (segment._chained & 2) == 0; + val incoming := p1 - at.apply(segment._points[2]); + # A corner flat or hollow: the segment before meets it by its face. + return manifold{} if incoming.cross(along) <= 0.017 * incoming.length * along.length; + val n_before := vec2{ incoming.y, -incoming.x }.normalized(); + return m if n_before.cross(m.normal) >= 0 && m.normal.cross(n) >= 0; + return manifold{}; +} + +# Whether a one-sided collider, a chain's segment or a one-way collider, lets +# a shape where a pose places it through, as it's behind or below it. +def space::behind_one_way(&this, c: u32, s: &shape, at: pose): bool { + val held := &this.colliders[c as u64]; + return false if held.is_grid(); + val placed := this.bodies[held.body as u64].at; + if held.made.shape.is_one_sided { + val n := placed.turn.apply(held.made.shape._normals[0]); + return n.dot(at.apply(s.middle()) - placed.apply(held.made.shape._points[0])) < 0; + } + return false if !held.made.one_way; + val g := gap_between(&held.made.shape, placed, s, at); + return g.distance <= 0 || g.normal.dot(placed.turn.apply(held.made.up)) < 0.7; +} + +# Whether a contact of a one-way collider holds: one beginning from its `up` +# side does, until the two part; one beginning otherwise passes through until +# then. +def space::one_way_holds(&mut this, k: u32, platform: u32, began: bool): bool { + val c := &mut this.contacts[k as u64]; + if !c.touching { + c.passing = false; + return false; + } + if began { + val held := &this.colliders[platform as u64]; + val up := this.bodies[held.body as u64].at.turn.apply(held.made.up); + # The normal from the platform toward what met it. + val toward := this.pairs[c.pair as u64].a == platform ? c.manifold.normal : c.manifold.normal * -1f; + c.passing = toward.dot(up) < 0.7; + } + return !c.passing; +} diff --git a/physics2d/character.sakura b/physics2d/character.sakura new file mode 100644 index 0000000..3271f1a --- /dev/null +++ b/physics2d/character.sakura @@ -0,0 +1,219 @@ +#! Contains `character`, a body a game walks, as Box2D's character mover is: +#! not a rigid body of the space, but a shape moved through it by casts, sliding +#! along what it meets, stepping up what's low enough, sticking to the ground as +#! it walks down slopes and off steps, riding what it stands on as that moves, +#! pushed out of what moves into it, and pushing what's dynamic before it. + +import std::math; +import malunal::linear; +module malunal::physics2d; + +#! A character's body, and what it stands on, as its last move found it. +pub struct character { + #! Its shape, about its origin, a capsule standing up as `shape::pill` + #! makes one. + pub var shape := shape::pill(0.6, 1.8); + #! Where its origin is. + pub var at: vec2; + #! Which way is up, against gravity, of length 1: its shape stands along + #! it, as on a planet, where up is away from the middle. + pub var up := vec2{ 0, 1 }; + #! How fast it moved in its last move, but for what it rode: what it was + #! asked to, less what it met. A game adds gravity to it while it's in the + #! air. + pub var velocity: vec2; + #! The steepest ground it stands on and walks up, in radians from flat. + pub var max_slope: f32 = 0.8; + #! The highest it steps up, as onto a stair, and the furthest down it keeps + #! to the ground, as walking down one. + pub var step_height: f32 = 0.35; + pub var snap: f32 = 0.35; + #! How far it keeps from what it meets. + pub var skin: f32 = 0.02; + #! Its mass, and the most force it pushes what's dynamic with. + pub var mass: f32 = 70; + pub var push: f32 = 500; + #! The layers of colliders it meets. + pub var mask: u32 = 0xFFFFFFFF; + #! A body of its own in the space, as a kinematic one moved with it so what + #! moves meets it, which it passes over. + pub var body: body_id; + #! Whether it stands on ground it may, and that ground: which way it faces, + #! its body, and how fast it moves where the character stands. + pub var grounded: bool; + pub var ground_normal := vec2{ 0, 1 }; + pub var ground: body_id; + pub var ground_velocity: vec2; +} + +#! Whether a character may stand on ground facing a direction. +pub def character::walkable(&this, normal: vec2): bool { + return normal.dot(this.up) >= math::cos(this.max_slope); +} + +#! Its pose: at its place, turned from standing along y to stand along its up. +pub def character::pose(&this): pose { + return this.pose_at(this.at); +} + +# Its pose, were it somewhere else. +def character::pose_at(&this, at: vec2): pose { + return pose::of(at, math::atan2(-this.up.x, this.up.y)); +} + +#! Moves a character through a step of `dt` seconds, at a velocity, as its +#! game asks, adding how fast what it stands on moves: pushed out of what it +#! overlaps, then cast along its motion, sliding along what it meets, stepping +#! up what's low enough while it's on the ground, and kept to the ground as it +#! walks down. Its velocity after is what it was asked, less what it met; what +#! it stands on is found again. +pub def space::move_character(&mut this, c: &mut character, velocity: vec2, dt: f32): void { + return if dt <= 0; + val was_grounded := c.grounded; + c.velocity = velocity; + this.push_character_out(c); + var motion := velocity * dt; + if was_grounded { + motion = motion + c.ground_velocity * dt; + } + for iteration in 0..4u { + if motion.length_squared < tiny * tiny { + break; + } + val hit := this.shape_cast(&c.shape, c.pose(), motion, c.mask, c.body) else { + c.at = c.at + motion; + break; + }; + c.at = c.at + motion * hit.fraction + hit.normal * c.skin; + var left := motion * (1 - hit.fraction); + val walkable := c.walkable(hit.normal); + if !walkable && was_grounded && this.step_up(c, velocity * dt) { + break; + } + # What's left slides along what it met: along a wall it can't walk up, + # not up it. + var n := hit.normal; + if !walkable && was_grounded { + val flat := n - c.up * n.dot(c.up); + if flat.length_squared > tiny { + n = flat.normalized(); + } + } + this.push_struck(c, &hit, dt); + left = left - n * math::min(left.dot(n), 0f); + c.velocity = c.velocity - n * math::min(c.velocity.dot(n), 0f); + motion = left; + } + # Kept to the ground walking down a slope or off a step, where it isn't + # moving up. + if was_grounded && c.velocity.dot(c.up) <= 0 && c.snap > 0 { + if this.shape_cast(&c.shape, c.pose(), c.up * -c.snap, c.mask, c.body) is some(down) { + if c.walkable(down.normal) { + c.at = c.at - c.up * (c.snap * down.fraction) + c.up * c.skin; + } + } + } + this.find_ground(c); +} + +# Finds what a character stands on, just below it. +def space::find_ground(&this, c: &mut character): void { + c.grounded = false; + c.ground = body_id{}; + c.ground_velocity = vec2::zero; + val below := this.shape_cast(&c.shape, c.pose(), c.up * (-3 * c.skin), c.mask, c.body) else { return; }; + return if !c.walkable(below.normal); + c.grounded = true; + c.ground_normal = below.normal; + c.ground = below.body; + val b := &this.bodies[below.body.index as u64]; + if b.kind != body_kind::static { + c.ground_velocity = b.velocity + spun(b.spin, c.at - b.center); + } + # Standing, it doesn't fall into the ground. + val falling := c.velocity.dot(c.up); + if falling < 0 { + c.velocity = c.velocity - c.up * falling; + } +} + +# Steps a character up onto what it walked into, where it's no higher than its +# step: raised, moved on as far as it walks this step, and lowered, where +# feeling further ahead finds ground it may stand on there. +def space::step_up(&this, c: &mut character, left: vec2): bool { + val ahead := left - c.up * left.dot(c.up); + return false if ahead.length_squared < tiny * tiny || c.step_height <= 0; + var rise := c.step_height; + if this.shape_cast(&c.shape, c.pose(), c.up * c.step_height, c.mask, c.body) is some(above) { + rise = math::max(c.step_height * above.fraction - c.skin, 0f); + } + return false if rise <= c.skin; + val raised := c.pose_at(c.at + c.up * rise); + # Felt for further ahead than its round foot reaches, however little it's + # left to move, so it steps only onto what's there to stand on, higher than + # it stands, and not onto the step's edge. + val reach := math::max(ahead.length, c.shape.radius + 2 * c.skin); + val probe := ahead.normalized() * reach; + var moved := probe; + if this.shape_cast(&c.shape, raised, probe, c.mask, c.body) is some(wall) { + moved = probe * wall.fraction; + } + return false if moved.length < 0.5 * reach; + val drop := c.up * -(rise + c.skin); + val landing := this.shape_cast(&c.shape, c.pose_at(raised.at + moved), drop, c.mask, c.body) else { return false; }; + return false if !c.walkable(landing.normal) || landing.fraction == 0; + return false if (rise + c.skin) * (1 - landing.fraction) <= c.skin; + # Then moved as far as it walks, and set down, on the step's edge, maybe, to + # walk on from. + val over := c.pose_at(raised.at + ahead * math::min(1f, moved.length / ahead.length)); + val down := this.shape_cast(&c.shape, over, drop, c.mask, c.body) else { return false; }; + c.at = over.at + drop * down.fraction + c.up * c.skin; + return true; +} + +# Pushes a character out of what it overlaps, as what moves into it does, a +# few times over, by the deepest each time. +def space::push_character_out(&this, c: &mut character): void { + for iteration in 0..4u { + var deepest: f32 = 0; + var away := vec2::zero; + val placed := c.pose(); + this.tree.query(c.shape.bounds(placed).grown(c.skin), def(leaf: u32, data: u64): bool { + return true if this.colliders[data].body == c.body.index || !this.passes(data as u32, &query_filter{ mask = c.mask }) || this.behind_one_way(data as u32, &c.shape, placed); + val held := &this.colliders[data]; + val at := this.bodies[held.body as u64].at; + if held.is_grid() { + this.grids[held.grid as u64].collide(at, &c.shape, placed, def(x: u32, y: u32, m: manifold): bool { + if m.depth > deepest { + deepest = m.depth; + away = m.normal; + } + return true; + }); + return true; + } + var m := collide(&held.made.shape, at, &c.shape, placed) else { return true; }; + if held.made.shape.is_one_sided { + m = chained(&held.made.shape, at, &c.shape, placed, m); + } + if m.depth > deepest { + deepest = m.depth; + away = m.normal; + } + return true; + }); + if deepest <= 0 { + return; + } + c.at = c.at + away * (deepest + c.skin); + } +} + +# Pushes a dynamic body a character walked into, by no more than its push. +def space::push_struck(&mut this, c: &character, hit: &space_cast, dt: f32): void { + return if !this.has(hit.body) || this.bodies[hit.body.index as u64].kind != body_kind::dynamic; + val into := -c.velocity.dot(hit.normal); + return if into <= 0; + val impulse := math::min(into * c.mass, c.push * dt); + this.apply_impulse(hit.body, -hit.normal * impulse, hit.point); +} diff --git a/physics2d/collide.sakura b/physics2d/collide.sakura new file mode 100644 index 0000000..21870d2 --- /dev/null +++ b/physics2d/collide.sakura @@ -0,0 +1,302 @@ +#! Contains collision between shapes: whether two meet, where they're placed, +#! and the `manifold` of where and how deep, which way to push them apart. +#! +#! Each shape is taken as a hull, its points where its pose places them, with +#! its radius around them: a circle of one point, a capsule of two, a polygon +#! of its corners. Two circles meet as their middles near; a circle and a hull +#! as the circle's middle nears the hull's edges, or lies within it; and two +#! hulls by the edge of either that holds them furthest apart, as the +#! separating axis theorem finds it. Where their hulls overlap, or their round +#! sides near along a face, the other's nearest edge is clipped to that face, +#! as Box2D clips one, so a box resting flat on another meets it at two +#! points; where only their round sides meet, they meet at one, along the line +#! between the hulls' nearest points. + +import std::math; +import malunal::linear; +module malunal::physics2d; + +#! A point where two shapes meet: midway between their surfaces, how deep the +#! one is within the other there, 0 where they touch and below where they're +#! apart within a margin, and the features of each that meet there, which stay +#! the same as they slide, so a solver knows the point from one step to the +#! next. +pub struct contact { + pub var point: vec2; + pub var depth: f32; + pub var id: u32; +} + +#! Where and how deep two shapes meet: the normal from the first toward the +#! second, along which the second is pushed out of the first, and one or two +#! points, as a box resting flat on another rests on two. +pub struct manifold { + pub var normal: vec2; + pub var points: contact[2]; + pub var count: u32; +} + +#! The deepest of its points. +pub val manifold::depth: f32 { + get => this.count == 0 ? 0f : this.count == 1 ? this.points[0].depth : math::max(this.points[0].depth, this.points[1].depth); +} + +#! The manifold turned around, of the second shape against the first. +pub def manifold::flipped(&this): manifold { + return manifold{ normal = this.normal * -1f, points = this.points, count = this.count }; +} + +# A shape's points where its pose places it, and its edges' normals. +struct hull { + var points: vec2[8]; + var normals: vec2[8]; + var count: u32; + var radius: f32; +} + +# Turned a number at a time, which sakurac keeps in registers. +def hull_of(s: &shape, at: pose): hull { + var made := hull{ count = s.count, radius = s.radius }; + val c := at.turn.c; + val sn := at.turn.s; + for i in 0..s.count { + val p := s.point(i); + val n := s.normal(i); + made.points[i] = vec2{ at.at.x + c * p.x - sn * p.y, at.at.y + sn * p.x + c * p.y }; + made.normals[i] = vec2{ c * n.x - sn * n.y, sn * n.x + c * n.y }; + } + return made; +} + +# A shape's own points and normals, unturned. +def own_hull(s: &shape): hull { + var made := hull{ count = s.count, radius = s.radius }; + for i in 0..s.count { + made.points[i] = s.point(i); + made.normals[i] = s.normal(i); + } + return made; +} + +#! Where two shapes meet, each where its pose places it, or nothing where they +#! don't: the manifold's normal from the first toward the second. Where a +#! margin is given, shapes apart by no more than it meet too, at points of a +#! depth below 0, as a solver's speculative contacts are, which keep what falls +#! from passing into what's below it in one step. +pub def collide(a: &shape, at_a: pose, b: &shape, at_b: pose, margin: f32 = 0): maybe { + # Worked among the first's own places, so only the second's points are + # turned, then the manifold turned back. + val found := collide_own(a, b, at_a.unapply_pose(at_b), margin) else { return nothing{}; }; + val c := at_a.turn.c; + val sn := at_a.turn.s; + var placed := manifold{ normal = vec2{ c * found.normal.x - sn * found.normal.y, sn * found.normal.x + c * found.normal.y }, count = found.count }; + for i in 0..found.count { + val p := found.points[i].point; + placed.points[i] = contact{ point = vec2{ at_a.at.x + c * p.x - sn * p.y, at_a.at.y + sn * p.x + c * p.y }, depth = found.points[i].depth, id = found.points[i].id }; + } + return placed; +} + +# The same of the second placed among the first's own places. +def collide_own(a: &shape, b: &shape, at_b: pose, margin: f32): maybe { + val ha := own_hull(a); + val hb := hull_of(b, at_b); + if ha.count == 1 && hb.count == 1 { + return circles(ha.points[0], ha.radius, hb.points[0], hb.radius, margin); + } + if hb.count == 1 { + return hull_and_circle(&ha, hb.points[0], hb.radius, margin); + } + if ha.count == 1 { + if hull_and_circle(&hb, ha.points[0], ha.radius, margin) is some(m) { + return m.flipped(); + } + return nothing{}; + } + return hulls(&ha, &hb, margin); +} + +#! Whether two shapes meet, each where its pose places it, touching among it. +pub def overlaps(a: &shape, at_a: pose, b: &shape, at_b: pose): bool { + return collide(a, at_a, b, at_b) is some(_); +} + +# A manifold of one point, between the surfaces of the first, at `on_a` +# within `radius_a` of it along the normal, and the second's, at `on_b` less +# `radius_b`. +def one_point(normal: vec2, on_a: vec2, radius_a: f32, on_b: vec2, radius_b: f32, depth: f32): manifold { + var made := manifold{ normal = normal, count = 1 }; + made.points[0] = contact{ point = ((on_a + normal * radius_a) + (on_b - normal * radius_b)) * 0.5, depth = depth }; + return made; +} + +def circles(a: vec2, ra: f32, b: vec2, rb: f32, margin: f32): maybe { + val between := b - a; + val distance := between.length; + return nothing{} if distance > ra + rb + margin; + val normal := distance > tiny ? between * (1 / distance) : vec2{ 0, 1 }; + return one_point(normal, a, ra, b, rb, ra + rb - distance); +} + +# A hull and a circle: within a polygon, pushed out by the face it's nearest; +# else by the hull's point nearest the circle's middle. +def hull_and_circle(h: &hull, c: vec2, radius: f32, margin: f32): maybe { + val reach := h.radius + radius; + # The face the middle is furthest in front of. + var face: u32 = 0; + var separation := -1e30f; + for i in 0..h.count { + val s := h.normals[i].dot(c - h.points[i]); + if s > separation { + separation = s; + face = i; + } + } + return nothing{} if separation > reach + margin; + if h.count >= 3 && separation <= 0 { + val n := h.normals[face]; + return one_point(n, c - n * separation, h.radius, c, radius, reach - separation); + } + var nearest := h.points[0]; + var best := 1e30f; + for i in 0..h.count { + val p := nearest_on_segment(c, h.points[i], h.points[(i + 1) % h.count]); + val d := (c - p).length_squared; + if d < best { + best = d; + nearest = p; + } + } + val distance := math::sqrt(best); + return nothing{} if distance > reach + margin; + val normal := distance > tiny ? (c - nearest) * (1 / distance) : h.normals[face]; + return one_point(normal, nearest, h.radius, c, radius, reach - distance); +} + +# How far in front of a hull's edge another hull lies, of the edge that holds +# it furthest: the edge, and the distance, below 0 where they overlap. +struct apart { + var edge: u32; + var separation: f32; +} + +def furthest_apart(from: &hull, other: &hull): apart { + var found := apart{ separation = -1e30f }; + for i in 0..from.count { + val n := from.normals[i]; + var least := 1e30f; + for j in 0..other.count { + least = math::min(least, n.dot(other.points[j] - from.points[i])); + } + if least > found.separation { + found = apart{ edge = i, separation = least }; + } + } + return found; +} + +# Two hulls of two or more points each. +def hulls(a: &hull, b: &hull, margin: f32): maybe { + val reach := a.radius + b.radius; + val of_a := furthest_apart(a, b); + return nothing{} if of_a.separation > reach + margin; + val of_b := furthest_apart(b, a); + return nothing{} if of_b.separation > reach + margin; + # The face of the first is taken where it's as good, so the same pair gives + # the same face from one frame to the next. + val flip := of_b.separation > of_a.separation + 1e-4; + val reference := flip ? b : a; + val incident := flip ? a : b; + val face := flip ? of_b.edge : of_a.edge; + val separation := flip ? of_b.separation : of_a.separation; + + if separation > 1e-4 && reach > 0 { + # Apart but for their round sides: they meet along the line between the + # hulls' nearest points, or along a face nearly that way. + var best := 1e30f; + var on_a := a.points[0]; + var on_b := b.points[0]; + for i in 0..edges_of(a) { + for j in 0..edges_of(b) { + val pair := nearest_of_segments(a.points[i], a.points[(i + 1) % a.count], b.points[j], b.points[(j + 1) % b.count]); + val d := (pair[1] - pair[0]).length_squared; + if d < best { + best = d; + on_a = pair[0]; + on_b = pair[1]; + } + } + } + val distance := math::sqrt(best); + return nothing{} if distance > reach + margin; + val normal := (on_b - on_a) * (1 / distance); + val along_face := flip ? normal * -1f : normal; + if along_face.dot(reference.normals[face]) < 0.995 { + return one_point(normal, on_a, a.radius, on_b, b.radius, reach - distance); + } + } + return clipped(reference, incident, face, flip, margin); +} + +# How many distinct edges a hull has: a capsule's two are one segment. +def edges_of(h: &hull): u32 { + return h.count == 2 ? 1 : h.count; +} + +# The incident hull's edge facing most against the reference face, clipped to +# the face's width: each point of it within reach of the face a contact, named +# by the face, the edge, and which end of it the point is of. +def clipped(reference: &hull, incident: &hull, face: u32, flip: bool, margin: f32): maybe { + val n := reference.normals[face]; + val v1 := reference.points[face]; + val v2 := reference.points[(face + 1) % reference.count]; + var edge: u32 = 0; + var least := 1e30f; + for i in 0..incident.count { + val d := n.dot(incident.normals[i]); + if d < least { + least = d; + edge = i; + } + } + var points: vec2[2] = [incident.points[edge], incident.points[(edge + 1) % incident.count]]; + val tangent := (v2 - v1).normalized(); + var kept: u32 = 2; + kept = clip(&mut points, kept, tangent * -1f, -tangent.dot(v1)); + return nothing{} if kept < 2; + kept = clip(&mut points, kept, tangent, tangent.dot(v2)); + return nothing{} if kept < 2; + + val reach := reference.radius + incident.radius; + var made := manifold{ normal = flip ? n * -1f : n }; + val flipped: u32 = flip ? 0x10000 : 0; + val named := flipped | (face << 8) | (edge << 1); + for i in 0..2u { + val s := n.dot(points[i] - v1); + continue if s > reach + margin; + # Midway between the reference's surface and the incident's. + val on_reference := points[i] - n * (s - reference.radius); + val on_incident := points[i] - n * incident.radius; + made.points[made.count] = contact{ point = (on_reference + on_incident) * 0.5, depth = reach - s, id = named | i as u32 }; + made.count++; + } + return nothing{} if made.count == 0; + return made; +} + +# Clips a segment to the side of a line where `normal.dot(p) <= offset`, as +# Sutherland and Hodgman clip, keeping two points where any of it is there. +def clip(points: &mut vec2[2], kept: u32, normal: vec2, offset: f32): u32 { + val d0 := normal.dot(points[0]) - offset; + val d1 := normal.dot(points[1]) - offset; + return 2 if d0 <= 0 && d1 <= 0; + return 0 if d0 > 0 && d1 > 0; + val t := d0 / (d0 - d1); + val crossing := points[0] + (points[1] - points[0]) * t; + if d0 > 0 { + points[0] = crossing; + } else { + points[1] = crossing; + } + return 2; +} diff --git a/physics2d/contacts.sakura b/physics2d/contacts.sakura new file mode 100644 index 0000000..ad37593 --- /dev/null +++ b/physics2d/contacts.sakura @@ -0,0 +1,474 @@ +#! Contains how a space finds which colliders are near one another, by the +#! boxes of its tree, and where those meet, as contacts kept from one step to +#! the next, so each begins with the impulses that held its bodies apart last. +#! Two shapes have one contact; a shape and a grid one for each solid cell they +#! meet, named by the cell, so it's kept as they slide. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics2d; + +#! Two colliders that began or stopped touching in a step: sensors among +#! them, which touch where they overlap. +pub struct contact_event { + pub var a: collider_id; + pub var b: collider_id; + #! Whether they began touching, or stopped. + pub var began: bool; + #! Whether either is a sensor. + pub var sensor: bool; +} + +# Two colliders whose grown boxes meet, the first's index the lesser, and +# their contacts, a list of them: none of sensors, which only note whether +# they overlap. +struct pair_record { + var a: u32; + var b: u32; + var contacts: u32 = 0xFFFFFFFF; + var touching: bool; + var sensor: bool; + var grid: bool; + var alive: bool; +} + +# Where two colliders meet, or a shape and one cell of a grid: the manifold, +# and the impulses that held them apart at each of its points last step. +struct contact_record { + var pair: u32; + var child: u32; # The cell, of a grid's. + var next: u32 = 0xFFFFFFFF; + var body_a: u32; + var body_b: u32; + var manifold: manifold; + var normal_impulse: f32[2]; + var tangent_impulse: f32[2]; + var friction: f32; + var restitution: f32; + var touching: bool; + var passing: bool; # Of a one-way collider's, met from below. + var seen: bool; + var alive: bool; +} + +# A cell a shape met, and how. +struct met_cell { + var cell: u32; + var manifold: manifold; +} + +# The key of a pair of colliders, whichever comes first. +def pair_key(a: u32, b: u32): u64 { + val low := math::min(a, b) as u64; + val high := math::max(a, b) as u64; + return (low << 32) | high; +} + +# Whether two colliders may meet: of two bodies, one of them dynamic, or one +# a sensor and the other not static, on layers each other's masks hold, not +# both grids, and not of bodies a joint keeps apart. +def space::may_meet(&this, a: u32, b: u32): bool { + val ca := &this.colliders[a as u64]; + val cb := &this.colliders[b as u64]; + return false if ca.body == cb.body || (ca.is_grid() && cb.is_grid()); + if !this.bodies[ca.body as u64].is_dynamic() && !this.bodies[cb.body as u64].is_dynamic() { + # A sensor meets what moves into it, kinematic as well as dynamic, but two + # standing still never meet. + return false if !ca.made.sensor && !cb.made.sensor; + return false if this.bodies[ca.body as u64].kind == body_kind::static && this.bodies[cb.body as u64].kind == body_kind::static; + } + return false if (ca.made.layers & cb.made.mask) == 0 || (cb.made.layers & ca.made.mask) == 0; + return !this.joined_apart(ca.body, cb.body); +} + +# Pairs each collider whose leaf moved with those its grown box newly meets. +def space::find_pairs(&mut this): void { + return if this.moved.length == 0; + var near := move(this.near); + for m in 0..this.moved.length { + val c := this.moved[m]; + continue if !this.colliders[c as u64].alive; + near.clear(); + this.tree.query(this.tree.box_of(this.colliders[c as u64].leaf), def(leaf: u32, data: u64): bool { + val other := data as u32; + # Where both moved, the one of the lesser index pairs them. + if other != c && !(this.colliders[data].moved && other < c) { + near.append(other); + } + return true; + }); + for k in 0..near.length { + val other := near[k]; + val key := pair_key(c, other); + if this.may_meet(c, other) && !this.pair_keys.contains(&key) { + this.make_pair(math::min(c, other), math::max(c, other)); + } + } + } + for m in 0..this.moved.length { + this.colliders[this.moved[m] as u64].moved = false; + } + this.moved.clear(); + this.near = move(near); +} + +def space::make_pair(&mut this, a: u32, b: u32): void { + var p: u32 = 0; + if this.free_pairs.length > 0 { + p = this.free_pairs[this.free_pairs.length - 1]; + this.free_pairs.truncate(); + } else { + p = this.pairs.length as u32; + this.pairs.append(pair_record{}); + } + val sensor := this.colliders[a as u64].made.sensor || this.colliders[b as u64].made.sensor; + val grid := this.colliders[a as u64].is_grid() || this.colliders[b as u64].is_grid(); + this.pairs[p as u64] = pair_record{ a = a, b = b, sensor = sensor, grid = grid, alive = true }; + this.pair_keys.set(pair_key(a, b), p); + if !sensor && !grid { + this.pairs[p as u64].contacts = this.make_contact(p, 0); + } +} + +# A new contact of a pair, put first of its list. +def space::make_contact(&mut this, p: u32, child: u32): u32 { + var k: u32 = 0; + if this.free_contacts.length > 0 { + k = this.free_contacts[this.free_contacts.length - 1]; + this.free_contacts.truncate(); + } else { + k = this.contacts.length as u32; + this.contacts.append(contact_record{}); + } + val a := this.pairs[p as u64].a; + val b := this.pairs[p as u64].b; + val ma := &this.colliders[a as u64].made; + val mb := &this.colliders[b as u64].made; + this.contacts[k as u64] = contact_record{ + pair = p, child = child, next = this.pairs[p as u64].contacts, + body_a = this.colliders[a as u64].body, body_b = this.colliders[b as u64].body, + friction = math::sqrt(ma.friction * mb.friction), restitution = math::max(ma.restitution, mb.restitution), alive = true, + }; + return k; +} + +def space::free_contact(&mut this, k: u32): void { + this.contacts[k as u64].alive = false; + this.free_contacts.append(k); +} + +# Frees a pair and its contacts, noting it stopped where it touched, and +# waking its bodies then where `wake` is given. +def space::drop_pair(&mut this, p: u32, wake: bool): void { + val pair := this.pairs[p as u64]; + if pair.touching { + this.note(p, false); + if wake { + this.wake_body(this.colliders[pair.a as u64].body); + this.wake_body(this.colliders[pair.b as u64].body); + } + } + var k := pair.contacts; + while k != none { + val next := this.contacts[k as u64].next; + this.free_contact(k); + k = next; + } + this.pair_keys.remove(&pair_key(pair.a, pair.b)); + this.pairs[p as u64].alive = false; + this.free_pairs.append(p); +} + +# Notes that a pair began or stopped touching. +def space::note(&mut this, p: u32, began: bool): void { + val a := this.pairs[p as u64].a; + val b := this.pairs[p as u64].b; + this.noted.append(contact_event{ + a = collider_id{ index = a, generation = this.colliders[a as u64].generation }, + b = collider_id{ index = b, generation = this.colliders[b as u64].generation }, + began = began, sensor = this.pairs[p as u64].sensor, + }); +} + +# Whether a body moves this step: dynamic or kinematic, and awake. +def space::moves(&this, b: u32): bool { + val body := &this.bodies[b as u64]; + return body.kind != body_kind::static && body.awake; +} + +# Where a pair's shapes meet: as the crew found it, where the step is solved on +# several threads, else found now. +def space::pair_manifold(&this, p: u32): manifold { + return this.found[p as u64] if this.threads > 1; + return this.manifold_of(this.pairs[p as u64].a, this.pairs[p as u64].b); +} + +# Finds where each pair of two shapes meets, on the crew, a block of pairs to +# each thread, as none needs another's: what it finds is put to use one pair at +# a time after, so a step gives the same on any number of threads. +def space::find_manifolds(&mut this): void { + this.found.clear(); + this.found.resize(this.pairs.length, manifold{}); + var job := pairs_job{ space = address(this) }; + val block := math::max(this.pairs.length / (this.threads as u64 * 8), 16u); + this.crew.run(run_pairs, address(&mut job) as *mut u8, this.pairs.length, block); +} + +struct pairs_job { + var space: *mut space; +} + +def run_pairs(context: *mut u8, begin: u64, end: u64): void { + val job := &through(context as *mut pairs_job); + val s := &mut through(job.space); + for p in begin..end { + val pair := &s.pairs[p]; + continue if !pair.alive || pair.sensor || pair.grid; + val ca := &s.colliders[pair.a as u64]; + val cb := &s.colliders[pair.b as u64]; + continue if !s.moves(ca.body) && !s.moves(cb.body); + continue if !s.tree.box_of(ca.leaf).overlaps(s.tree.box_of(cb.leaf)); + s.found[p] = s.manifold_of(pair.a, pair.b); + } +} + +# Finds where each pair of a moving body meets, dropping those whose grown +# boxes no longer meet. +def space::update_contacts(&mut this): void { + if this.threads > 1 { + this.find_manifolds(); + } + for p in 0..this.pairs.length { + continue if !this.pairs[p].alive; + val a := this.pairs[p].a; + val b := this.pairs[p].b; + val ba := this.colliders[a as u64].body; + val bb := this.colliders[b as u64].body; + continue if !this.moves(ba) && !this.moves(bb); + if !this.tree.box_of(this.colliders[a as u64].leaf).overlaps(this.tree.box_of(this.colliders[b as u64].leaf)) { + this.drop_pair(p as u32, false); + continue; + } + var touching := false; + if this.pairs[p].sensor { + touching = this.sensed(a, b); + } else if this.pairs[p].grid { + touching = this.update_grid_contacts(p as u32); + } else { + val k := this.pairs[p].contacts; + val before := this.contacts[k as u64].touching; + touching = this.update_contact(k, this.pair_manifold(p as u32)); + if this.colliders[a as u64].made.one_way { + touching = this.one_way_holds(k, a, !before); + } else if this.colliders[b as u64].made.one_way { + touching = this.one_way_holds(k, b, !before); + } + } + if touching != this.pairs[p].touching { + this.pairs[p].touching = touching; + this.note(p as u32, touching); + if touching && !this.pairs[p].sensor { + this.note_hit(p as u32); + } + } + # What touches a sleeping body, moving, wakes it, as a lift that sets off + # wakes what rests on it. + if touching { + this.wake_if_pushed(ba, bb); + this.wake_if_pushed(bb, ba); + } + } +} + +# Wakes a sleeping dynamic body where what touches it is awake and moves it: a +# dynamic body, or a kinematic one moving. +def space::wake_if_pushed(&mut this, b: u32, by: u32): void { + return if this.bodies[b as u64].awake || this.bodies[b as u64].kind != body_kind::dynamic; + val other := &this.bodies[by as u64]; + if other.awake && (other.kind == body_kind::dynamic || other.velocity.length_squared > 0 || other.spin != 0) { + this.wake_body(b); + } +} + +# Where two colliders' shapes meet, within the speculative margin. +def space::manifold_of(&this, a: u32, b: u32): manifold { + val ca := &this.colliders[a as u64]; + val cb := &this.colliders[b as u64]; + val at_a := this.bodies[ca.body as u64].at; + val at_b := this.bodies[cb.body as u64].at; + val m := collide(&ca.made.shape, at_a, &cb.made.shape, at_b, this.speculative) else { return manifold{}; }; + return chained(&ca.made.shape, at_a, &cb.made.shape, at_b, m) if ca.made.shape.is_one_sided; + return chained(&cb.made.shape, at_b, &ca.made.shape, at_a, m.flipped()).flipped() if cb.made.shape.is_one_sided; + return m; +} + +# Whether a sensor's pair overlaps: a shape and a shape, or a shape and a +# grid. +def space::sensed(&this, a: u32, b: u32): bool { + val ca := &this.colliders[a as u64]; + val cb := &this.colliders[b as u64]; + val at_a := this.bodies[ca.body as u64].at; + val at_b := this.bodies[cb.body as u64].at; + return this.grids[ca.grid as u64].overlaps(at_a, &cb.made.shape, at_b) if ca.is_grid(); + return this.grids[cb.grid as u64].overlaps(at_b, &ca.made.shape, at_a) if cb.is_grid(); + return overlaps(&ca.made.shape, at_a, &cb.made.shape, at_b); +} + +# Gives a contact a manifold, each point beginning with the impulses of last +# step's point of the same features. +# @returns Whether it touches, within the speculative margin. +def space::update_contact(&mut this, k: u32, found: manifold): bool { + val c := &mut this.contacts[k as u64]; + var normal: f32[2] = [0, 0]; + var tangent: f32[2] = [0, 0]; + for i in 0..found.count { + for j in 0..c.manifold.count { + if found.points[i].id == c.manifold.points[j].id { + normal[i] = c.normal_impulse[j]; + tangent[i] = c.tangent_impulse[j]; + } + } + } + c.manifold = found; + c.normal_impulse = normal; + c.tangent_impulse = tangent; + c.touching = found.count > 0; + c.seen = true; + return c.touching; +} + +# Finds the solid cells a shape meets of a grid, a contact for each, keeping +# those it met last step and dropping those it no longer meets. +# @returns Whether any touches. +def space::update_grid_contacts(&mut this, p: u32): bool { + val a := this.pairs[p as u64].a; + val b := this.pairs[p as u64].b; + # The grid as the first, its normals from each cell toward the shape, + # turned back where the shape is the pair's first. + val grid_first := this.colliders[a as u64].is_grid(); + val g := grid_first ? a : b; + val s := grid_first ? b : a; + var met := move(this.met); + met.clear(); + val held := &this.colliders[g as u64]; + val shaped := &this.colliders[s as u64]; + val cells := &this.grids[held.grid as u64]; + val width := cells.width; + cells.collide(this.bodies[held.body as u64].at, &shaped.made.shape, this.bodies[shaped.body as u64].at, def(x: u32, y: u32, found: manifold): bool { + met.append(met_cell{ cell = y * width + x, manifold = grid_first ? found : found.flipped() }); + return true; + }, this.speculative); + var k := this.pairs[p as u64].contacts; + while k != none { + this.contacts[k as u64].seen = false; + k = this.contacts[k as u64].next; + } + var touching := false; + for i in 0..met.length { + var found := this.pairs[p as u64].contacts; + while found != none && this.contacts[found as u64].child != met[i].cell { + found = this.contacts[found as u64].next; + } + if found == none { + found = this.make_contact(p, met[i].cell); + this.pairs[p as u64].contacts = found; + } + if this.update_contact(found, met[i].manifold) { + touching = true; + } + } + this.met = move(met); + # Those not met this step are dropped. + var previous: u32 = none; + k = this.pairs[p as u64].contacts; + while k != none { + val next := this.contacts[k as u64].next; + if !this.contacts[k as u64].seen { + if previous == none { + this.pairs[p as u64].contacts = next; + } else { + this.contacts[previous as u64].next = next; + } + this.free_contact(k); + } else { + previous = k; + } + k = next; + } + return touching; +} + +#! Two colliders that began touching in a step faster than the space's +#! `hit_speed`, as something landing does: which, where, the normal from the +#! first toward the second, and how fast they met along it, as a sound of it +#! might be loud. +pub struct hit_event { + pub var a: collider_id; + pub var b: collider_id; + pub var point: vec2; + pub var normal: vec2; + pub var speed: f32; +} + +#! The hits of the last step. +pub def space::hits(&this): span { + return this.struck.span; +} + +# How fast a body's place moves, of a place of space. +def space::speed_at(&this, index: u32, at: vec2): vec2 { + val b := &this.bodies[index as u64]; + val r := at - b.center; + return b.velocity + spun(b.spin, r); +} + +# Notes how hard a pair that began touching met, where it met faster than the +# hit speed: at its first point, as the step began. +def space::note_hit(&mut this, p: u32): void { + var k := this.pairs[p as u64].contacts; + while k != none && this.contacts[k as u64].manifold.count == 0 { + k = this.contacts[k as u64].next; + } + return if k == none; + val c := &this.contacts[k as u64]; + val point := c.manifold.points[0].point; + val n := c.manifold.normal; + val speed := -n.dot(this.speed_at(c.body_b, point) - this.speed_at(c.body_a, point)); + return if speed < this.hit_speed; + val a := this.pairs[p as u64].a; + val b := this.pairs[p as u64].b; + this.struck.append(hit_event{ + a = collider_id{ index = a, generation = this.colliders[a as u64].generation }, + b = collider_id{ index = b, generation = this.colliders[b as u64].generation }, + point = point, normal = n, speed = speed, + }); +} + +#! Visits each pair of colliders touching as the last step left them, a +#! sensor's among them where it overlaps what it meets, as `visit(a, b, +#! sensor)`, until it gives false: what began and stopped touching since a +#! step before, by what it visited then, however colliders were taken away +#! and attached between. +pub def space::each_touching(&this, visit: F): void where F: invokable { + for p in 0..this.pairs.length { + val pair := &this.pairs[p]; + continue if !pair.alive || !pair.touching; + return if !visit(this.named(pair.a), this.named(pair.b), pair.sensor); + } +} +#! Visits each point of each contact touching, as `visit(a, b, point, normal, +#! depth)`, of its two colliders, its normal from the first toward the +#! second, until it gives false, as gizmos draw them. +pub def space::each_contact(&this, visit: F): void where F: invokable { + for k in 0..this.contacts.length { + val c := &this.contacts[k]; + continue if !c.alive || !c.touching; + val pair := &this.pairs[c.pair as u64]; + val a := collider_id{ index = pair.a, generation = this.colliders[pair.a as u64].generation }; + val b := collider_id{ index = pair.b, generation = this.colliders[pair.b as u64].generation }; + for i in 0..c.manifold.count { + return if !visit(a, b, c.manifold.points[i].point, c.manifold.normal, c.manifold.points[i].depth); + } + } +} \ No newline at end of file diff --git a/physics2d/continuous.sakura b/physics2d/continuous.sakura new file mode 100644 index 0000000..421a6b3 --- /dev/null +++ b/physics2d/continuous.sakura @@ -0,0 +1,120 @@ +#! Contains continuous collision, as Box2D's keeps a fast body from passing +#! through what's thin: a dynamic body that moved further in a step than half +#! the least its shapes reach is swept, from where it began the step to where +#! it ended it, against what stands still, and put back where it first comes +#! within the slop of what it met, its velocity kept, so the next step's +#! contacts stop it there. A bullet is swept against moving bodies too, where +#! they ended the step, as a shot against a crate. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics2d; + +# A body moving fast enough this step to pass through something thin, and how +# it moved. +struct fast_body { + var body: u32; + var moved: sweep; +} + +# Notes a body that moved fast enough to be swept, as the step ends. +def space::note_fast(&mut this, b: u32, moved: sweep): void { + val body := &this.bodies[b as u64]; + return if !this.continuous || body.kind != body_kind::dynamic || body.least <= 0; + val travel := (moved.c2 - moved.c1).length + math::abs(angle_between(moved.q2, moved.q1)) * body.extent; + if travel > 0.5 * body.least { + this.fast.append(fast_body{ body = b, moved = moved }); + } +} + +# Sweeps the fast bodies, bullets last, so they meet the rest where they end +# up, and places their colliders. +def space::sweep_fast(&mut this): void { + var fast := move(this.fast); + for pass in 0..2u { + for i in 0..fast.length { + val bullet := this.bodies[fast[i].body as u64].bullet; + continue if bullet != (pass == 1); + this.sweep_body(&fast[i]); + this.place_colliders(fast[i].body); + } + } + fast.clear(); + this.fast = move(fast); +} + +# Puts a fast body back where it first meets what it may pass through. +def space::sweep_body(&mut this, f: &fast_body): void { + val b := f.body; + val bullet := this.bodies[b as u64].bullet; + val target := this.slop; + val tolerance := 0.25 * this.slop; + var first: f32 = 1; + var c := this.bodies[b as u64].colliders; + while c != none { + val own := &this.colliders[c as u64]; + if !own.made.sensor && !own.is_grid() { + val start := f.moved.at(0); + val box := own.made.shape.bounds(start).merged(own.made.shape.bounds(f.moved.at(1))); + this.tree.query(box, def(leaf: u32, data: u64): bool { + val other := &this.colliders[data]; + return true if other.body == b || other.made.sensor; + return true if (other.made.layers & own.made.mask) == 0 || (own.made.layers & other.made.mask) == 0; + val held := &this.bodies[other.body as u64]; + return true if held.kind != body_kind::static && (!bullet || held.bullet); + return true if this.joined_apart(b, other.body); + val still := sweep::still(held.at); + if other.is_grid() { + val cells := &this.grids[other.grid as u64]; + cells.cells_in(local_box(box, held.at), def(x: u32, y: u32): bool { + val cell := cells.box_of(x, y); + val solid := shape::box(cell.half_size, cell.center); + val t := impact_of(&solid, &still, &own.made.shape, &f.moved, target, tolerance); + if t > 0 && t < first { + first = t; + } + return true; + }); + return true; + } + return true if this.behind_one_way(data as u32, &own.made.shape, start); + val t := impact_of(&other.made.shape, &still, &own.made.shape, &f.moved, target, tolerance); + if t > 0 && t < first { + first = t; + } + return true; + }); + } + c = this.colliders[c as u64].next; + } + return if first >= 1; + val at := f.moved.at(first); + this.bodies[b as u64].at = at; + this.bodies[b as u64].center = at.apply(this.bodies[b as u64].local_center); +} + +# When a fast shape first meets what stands still: where they touch as the +# step begins, as a corner resting on the ground does, when a small circle +# about the fast shape's middle first meets it, so its middle at least never +# passes through, as Box2D finds it. +def impact_of(still_shape: &shape, still: &sweep, fast: &shape, moved: &sweep, target: f32, tolerance: f32): f32 { + val t := time_of_impact(still_shape, still, fast, moved, target, tolerance); + return t if t > 0; + val core := shape::circle(0.25 * fast.least_reach(), fast.middle()); + return time_of_impact(still_shape, still, &core, moved, target, tolerance); +} + +# A box of the plane as one of a pose's own places, holding it however it's +# turned. +def local_box(box: aabb, at: pose): aabb { + val corners: vec2[4] = [box.min, vec2{ box.max.x, box.min.y }, box.max, vec2{ box.min.x, box.max.y }]; + var low := at.unapply(corners[0]); + var high := low; + for k in 1..4u { + val p := at.unapply(corners[k]); + low = low.min(p); + high = high.max(p); + } + return aabb{ low, high }; +} diff --git a/physics2d/crew.sakura b/physics2d/crew.sakura new file mode 100644 index 0000000..8e532de --- /dev/null +++ b/physics2d/crew.sakura @@ -0,0 +1,140 @@ +#! Contains `crew`: the threads a space solves a step's colors on, besides +#! its caller's, started as a step first asks for more than one and kept until +#! the space closes. Each job is a number of things, taken a block at a time by +#! whichever thread is free, the caller among them, which returns once all are +#! done. Between jobs, as a step's come one after another, the threads spin a +#! little before sleeping, so a job begins in a microsecond rather than the +#! tens a sleeping thread takes to wake, as Box2D's workers spin. They spin by +#! reading what they wait on: `system::pause` is the system's wait for a signal, +#! not the processor's hint that a thread spins. + +import system; +import std::containers; +import std::thread; +module malunal::physics2d; + +# What the threads are given to do: a function for each range of things. +struct crew_job { + var run: def(*mut u8, u64, u64): void; + var context: *mut u8; + var count: u64; + var block: u64; +} + +# What the threads share, on the heap, so it stays where it is. +struct crew_state { + var job: crew_job; + var next: atomic; # The job's round, high, and the next thing to take, low. + var done: atomic; # How many things are done. + var round: atomic; # Counts jobs, and the threads wait on it. + var sleeping: atomic; # How many threads sleep rather than spin. + var stopping: atomic; +} + +# How many times a thread spins waiting for a job before it sleeps. +const spins: u32 = 200000; + +# The threads a space solves on, besides its caller's. +struct crew : owning { + var shared: *mut crew_state; + var threads: vector>; +} + +# Starts threads, so there are as many as asked for in all, the caller's among +# them, where there aren't. +def crew::start(&mut this, count: u32): void { + if this.shared != null && this.threads.length + 1 != count as u64 { + this.close(); + } + return if this.shared != null || count <= 1; + this.shared = raw_allocate_zeroed(size_of::()) as *mut crew_state; + for _ in 1..count { + var started := thread::spawn_with(work, this.shared) else (_) { break; }; + this.threads.append(move(started)); + } +} + +# Runs a function over ranges of a job's things, a block at a time, on this +# thread and the crew's, and returns once all are done. +def crew::run(&mut this, run: def(*mut u8, u64, u64): void, context: *mut u8, count: u64, block: u64): void { + return if count == 0; + if this.shared == null || count <= block { + run(context, 0, count); + return; + } + val s := &mut through(this.shared); + # The next round's things first, so a thread late from the last takes none + # of this job's by the last's function. + val round := s.round.load(order::relaxed) + 1; + s.next.store((round as u64) << 32, order::release); + s.job = crew_job{ run = run, context = context, count = count, block = block }; + s.done.store(0, order::relaxed); + s.round.store(round, order::release); + if s.sleeping.load(order::acquire) > 0 { + _ = system::futex_wake(word_of(&mut s.round), 0x7FFFFFFF); + } + drain(s, round); + while s.done.load(order::acquire) < count { + } +} + +pub def crew::close(&mut this): void { + if this.shared != null { + val s := &mut through(this.shared); + s.stopping.store(1, order::release); + _ = s.round.fetch_add(1, order::release); + _ = system::futex_wake(word_of(&mut s.round), 0x7FFFFFFF); + this.threads.close(); + raw_release(this.shared as *mut u8); + this.shared = null; + } + this.threads.close(); +} + +# What each thread does: waits for a job, spinning then sleeping, and takes +# its things until none are left. +def work(shared: *mut crew_state): void { + val s := &mut through(shared); + var seen: u32 = 0; + while true { + var round := s.round.load(order::acquire); + var spun: u32 = 0; + while round == seen { + if spun < spins { + spun++; + } else { + _ = s.sleeping.fetch_add(1, order::acq_rel); + if s.round.load(order::acquire) == seen { + _ = system::futex_wait(word_of(&mut s.round), seen, -1); + } + _ = s.sleeping.fetch_sub(1, order::acq_rel); + } + round = s.round.load(order::acquire); + } + seen = round; + return if s.stopping.load(order::acquire) != 0; + drain(s, round); + } +} + +# Takes blocks of a round's job, running its function over each, until none +# are left, or the round has passed. +def drain(s: &mut crew_state, round: u32): void { + val job := s.job; + while true { + val held := s.next.load(order::acquire); + return if (held >> 32) as u32 != round; + val at := held & 0xFFFFFFFF; + return if at >= job.count; + val claimed := s.next.compare_exchange_weak(held, held + job.block, order::acq_rel, order::acquire); + continue if claimed is error(_); + val end := at + job.block < job.count ? at + job.block : job.count; + job.run(job.context, at, end); + _ = s.done.fetch_add(end - at, order::acq_rel); + } +} + +# The word of an atomic, which the system's futexes wait on. +def word_of(of: &mut atomic): *mut u32 { + return (address(of) as *mut atomic) as *mut u32; +} diff --git a/physics2d/distance.sakura b/physics2d/distance.sakura new file mode 100644 index 0000000..915b571 --- /dev/null +++ b/physics2d/distance.sakura @@ -0,0 +1,355 @@ +#! Contains how far apart two shapes are, their nearest places found as +#! Gilbert, Johnson, and Keerthi's GJK finds them; a shape cast along a motion, +#! to where it first meets another; and the time of impact of two shapes each +#! swept through a step, moving and turning, as continuous collision asks. +#! +#! GJK finds the place of the shapes' difference, every place of the second +#! less every place of the first, nearest the origin, by a triangle of its +#! corners at most, each step adding the corner furthest toward the origin and +#! keeping only what the nearest place lies on, as Box2D's distance does. It +#! works each shape's core, its points without their radius, then takes the +#! radii off, so a circle's nearest place is as exact as a box's. +#! +#! A cast, and a time of impact, advance conservatively, as Mirtich's do: each +#! moves the shapes as far as the gap between them, over how fast they can +#! close it, says they can't yet meet, so neither ever passes through what it +#! meets. + +import std::math; +import malunal::linear; +module malunal::physics2d; + +#! How far apart two shapes are, and the places of each nearest the other. +pub struct gap { + #! The places of the first's surface and the second's nearest one another: + #! one place, midway, where they meet. + pub var on_a: vec2; + pub var on_b: vec2; + #! The direction from the first toward the second, of length 1, or none + #! where they meet. + pub var normal: vec2; + #! How far apart their surfaces are: 0 where they meet. + pub var distance: f32; +} + +#! Where a shape cast along a motion first met another: how far along the +#! motion, as a fraction of it, the place of the other's surface it met, and +#! which way that surface faces, toward the shape cast. +pub struct cast_hit { + pub var fraction: f32; + pub var point: vec2; + pub var normal: vec2; +} + +# A corner of the shapes' difference, of a point of each, and its weight in +# the nearest place. +struct corner { + var on_a: vec2; + var on_b: vec2; + var w: vec2; + var weight: f32; + var ia: u32; + var ib: u32; +} + +# As many as three corners, the nearest place lying among them. +struct simplex { + var corners: corner[3]; + var count: u32; +} + +# The point of a shape furthest along a direction of the plane, where a pose +# places it. +def support_of(s: &shape, at: &pose, direction: vec2): u32 { + val d := at.turn.unapply(direction); + var best: u32 = 0; + var most := s.point(0).dot(d); + for i in 1..s.count { + val reach := s.point(i).dot(d); + if reach > most { + most = reach; + best = i; + } + } + return best; +} + +def corner_of(a: &shape, at_a: &pose, ia: u32, b: &shape, at_b: &pose, ib: u32): corner { + val pa := at_a.apply(a.point(ia)); + val pb := at_b.apply(b.point(ib)); + return corner{ on_a = pa, on_b = pb, w = pb - pa, weight = 1, ia = ia, ib = ib }; +} + +# The nearest place of a segment of the difference to the origin, keeping only +# the corner it's at where it's at one. +def solve2(x: &mut simplex): void { + val w1 := x.corners[0].w; + val w2 := x.corners[1].w; + val e12 := w2 - w1; + val d12_2 := -w1.dot(e12); + if d12_2 <= 0 { + x.corners[0].weight = 1; + x.count = 1; + return; + } + val d12_1 := w2.dot(e12); + if d12_1 <= 0 { + x.corners[0] = x.corners[1]; + x.corners[0].weight = 1; + x.count = 1; + return; + } + val inv := 1 / (d12_1 + d12_2); + x.corners[0].weight = d12_1 * inv; + x.corners[1].weight = d12_2 * inv; + x.count = 2; +} + +# The same of a triangle, by which of its corners, edges, or inside the +# origin's nearest place is in, as Box2D's distance finds it. +def solve3(x: &mut simplex): void { + val w1 := x.corners[0].w; + val w2 := x.corners[1].w; + val w3 := x.corners[2].w; + val e12 := w2 - w1; + val d12_1 := w2.dot(e12); + val d12_2 := -w1.dot(e12); + val e13 := w3 - w1; + val d13_1 := w3.dot(e13); + val d13_2 := -w1.dot(e13); + val e23 := w3 - w2; + val d23_1 := w3.dot(e23); + val d23_2 := -w2.dot(e23); + val n123 := e12.cross(e13); + val d123_1 := n123 * w2.cross(w3); + val d123_2 := n123 * w3.cross(w1); + val d123_3 := n123 * w1.cross(w2); + if d12_2 <= 0 && d13_2 <= 0 { + x.corners[0].weight = 1; + x.count = 1; + return; + } + if d12_1 > 0 && d12_2 > 0 && d123_3 <= 0 { + val inv := 1 / (d12_1 + d12_2); + x.corners[0].weight = d12_1 * inv; + x.corners[1].weight = d12_2 * inv; + x.count = 2; + return; + } + if d13_1 > 0 && d13_2 > 0 && d123_2 <= 0 { + val inv := 1 / (d13_1 + d13_2); + x.corners[0].weight = d13_1 * inv; + x.corners[1] = x.corners[2]; + x.corners[1].weight = d13_2 * inv; + x.count = 2; + return; + } + if d12_1 <= 0 && d23_2 <= 0 { + x.corners[0] = x.corners[1]; + x.corners[0].weight = 1; + x.count = 1; + return; + } + if d13_1 <= 0 && d23_1 <= 0 { + x.corners[0] = x.corners[2]; + x.corners[0].weight = 1; + x.count = 1; + return; + } + if d23_1 > 0 && d23_2 > 0 && d123_1 <= 0 { + val inv := 1 / (d23_1 + d23_2); + x.corners[0] = x.corners[2]; + x.corners[0].weight = d23_2 * inv; + x.corners[1].weight = d23_1 * inv; + x.count = 2; + return; + } + val whole := d123_1 + d123_2 + d123_3; + # A triangle of no area, its corners in a line: none holds the origin. + if !(whole > 0) { + x.corners[0].weight = 1; + x.count = 1; + return; + } + val inv := 1 / whole; + x.corners[0].weight = d123_1 * inv; + x.corners[1].weight = d123_2 * inv; + x.corners[2].weight = d123_3 * inv; + x.count = 3; +} + +# Which way the next corner is looked for: toward the origin from the nearest +# corner, or across the nearest edge, on the origin's side. +def search_direction(x: &simplex): vec2 { + return x.corners[0].w * -1f if x.count == 1; + val e12 := x.corners[1].w - x.corners[0].w; + return e12.perpendicular() if e12.cross(x.corners[0].w * -1f) > 0; + return vec2{ e12.y, -e12.x }; +} + +#! How far apart two shapes are, each where its pose places it, and the places +#! of each nearest the other: none apart where they meet. +pub def gap_between(a: &shape, at_a: pose, b: &shape, at_b: pose): gap { + var x := simplex{ count = 1 }; + x.corners[0] = corner_of(a, &at_a, 0, b, &at_b, 0); + var saved_a: u32[3] = [0, 0, 0]; + var saved_b: u32[3] = [0, 0, 0]; + for iteration in 0..20u { + val saved := x.count; + for i in 0..saved { + saved_a[i] = x.corners[i].ia; + saved_b[i] = x.corners[i].ib; + } + if x.count == 2 { + solve2(&mut x); + } else if x.count == 3 { + solve3(&mut x); + } + # Three corners hold the origin: the cores overlap. + if x.count == 3 { + break; + } + val d := search_direction(&x); + if d.length_squared < tiny * tiny { + break; + } + val ia := support_of(a, &at_a, d * -1f); + val ib := support_of(b, &at_b, d); + # A corner it has already found makes no progress. + var again := false; + for i in 0..saved { + if saved_a[i] == ia && saved_b[i] == ib { + again = true; + } + } + if again { + break; + } + x.corners[x.count] = corner_of(a, &at_a, ia, b, &at_b, ib); + x.count++; + } + # The corner added last solved with the rest, where the passes ran out. + if x.count == 2 { + solve2(&mut x); + } else if x.count == 3 { + solve3(&mut x); + } + var on_a := vec2::zero; + var on_b := vec2::zero; + for i in 0..x.count { + on_a = on_a + x.corners[i].on_a * x.corners[i].weight; + on_b = on_b + x.corners[i].on_b * x.corners[i].weight; + } + if x.count == 3 { + on_b = on_a; + } + val between := on_b - on_a; + val cores := between.length; + val reach := a.radius + b.radius; + if cores > reach && cores > tiny { + val normal := between * (1 / cores); + return gap{ on_a = on_a + normal * a.radius, on_b = on_b - normal * b.radius, normal = normal, distance = cores - reach }; + } + # They meet: midway between their surfaces along the line between their + # cores, where they have one. + val normal := cores > tiny ? between * (1 / cores) : vec2::zero; + val middle := ((on_a + normal * a.radius) + (on_b - normal * b.radius)) * 0.5; + return gap{ on_a = middle, on_b = middle, normal = normal, distance = 0 }; +} + +#! Where a shape, `b`, cast along a motion of the plane from where its pose +#! places it, first meets another, `a`, which stays where its pose places it: +#! within `tolerance` of its surface, a little short of touching, so what's +#! moved there doesn't overlap. Nothing where it doesn't meet it within the +#! motion; a fraction of 0 where they meet as it begins, its normal back along +#! the motion. +pub def shape_cast(a: &shape, at_a: pose, b: &shape, at_b: pose, motion: vec2, tolerance: f32 = 0.0025): maybe { + val target := 0.5 * tolerance; + var t: f32 = 0; + var at := at_b; + for iteration in 0..30u { + val g := gap_between(a, at_a, b, at); + if g.distance <= tolerance { + val back := g.distance > 0 ? g.normal : motion.normalized() * -1f; + return cast_hit{ fraction = t, point = g.on_a, normal = back }; + } + val approach := -motion.dot(g.normal); + return nothing{} if approach <= tiny; + t += (g.distance - target) / approach; + return nothing{} if t > 1; + at = pose{ at = at_b.at + motion * t, turn = at_b.turn }; + } + val g := gap_between(a, at_a, b, at); + return cast_hit{ fraction = t, point = g.on_a, normal = g.normal }; +} + +#! How a body moves through a step: its center of mass, of its own places, +#! where that center begins and ends the step, and how it's turned as it begins +#! and ends it, turning the shorter way between. +pub struct sweep { + pub var local_center: vec2; + pub var c1: vec2; + pub var c2: vec2; + pub var q1 := rot::identity; + pub var q2 := rot::identity; +} + +#! A sweep standing still where a pose places a body. +pub def sweep::still(at: pose, local_center: vec2 = vec2::zero): sweep { + val center := at.apply(local_center); + return sweep{ local_center = local_center, c1 = center, c2 = center, q1 = at.turn, q2 = at.turn }; +} + +#! Where it places its body a fraction of the way through the step. +pub def sweep::at(&this, t: f32): pose { + val turn := rot::of(angle_between(this.q2, this.q1) * t) * this.q1; + val center := this.c1.lerp(this.c2, t); + return pose{ at = center - turn.apply(this.local_center), turn = turn }; +} + +# How far a shape's surface reaches from a place of its own. +def reach_from(s: &shape, center: vec2): f32 { + var most: f32 = 0; + for i in 0..s.count { + most = math::max(most, (s.point(i) - center).length); + } + return most + s.radius; +} + +#! When, as a fraction of the step, two shapes each swept through it first come +#! within `target` of one another, to within `tolerance`, as their sweeps move +#! and turn them: 1 where they don't. Each moves no further than they can, as +#! fast as they close and turn, without meeting, so what's found is never past +#! where they meet. +pub def time_of_impact(a: &shape, sa: &sweep, b: &shape, sb: &sweep, target: f32, tolerance: f32): f32 { + val turn_a := math::abs(angle_between(sa.q2, sa.q1)) * reach_from(a, sa.local_center); + val turn_b := math::abs(angle_between(sb.q2, sb.q1)) * reach_from(b, sb.local_center); + val moved := (sb.c2 - sb.c1) - (sa.c2 - sa.c1); + var t: f32 = 0; + for iteration in 0..50u { + val g := gap_between(a, sa.at(t), b, sb.at(t)); + return t if g.distance <= target + tolerance; + val closing := -moved.dot(g.normal) + turn_a + turn_b; + return 1 if closing <= tiny; + t += (g.distance - target) / closing; + return 1 if t >= 1; + } + return t; +} + +# How far a shape reaches at least from its middle: a circle's or a capsule's +# radius, or the nearest of a polygon's edges, as a body may move without +# passing through what's in its way. +def shape::least_reach(&this): f32 { + return this.radius if this.kind != shape_kind::polygon; + var middle := vec2::zero; + for i in 0..this.count { + middle = middle + this.point(i); + } + middle = middle * (1 / this.count as f32); + var least := 1e30f; + for i in 0..this.count { + least = math::min(least, this.normal(i).dot(this.point(i) - middle)); + } + return least + this.radius; +} diff --git a/physics2d/drive_joints.sakura b/physics2d/drive_joints.sakura new file mode 100644 index 0000000..94a890e --- /dev/null +++ b/physics2d/drive_joints.sakura @@ -0,0 +1,174 @@ +#! Contains how a step solves the joints that slide and drive, as Box2D's soft +#! step solves them: a prismatic joint holds its bodies to its axis and turning +#! together, sliding between its limits, by its motor, or springily; a wheel +#! holds them to its axis alone, riding it on its spring, its motor turning +#! the wheel; a motor joint drives `b` toward a place and an angle of `a`'s +#! own; and a mouse joint pulls a place of `b` toward a target. + +import std::math; +import malunal::linear; +module malunal::physics2d; + +# A sliding joint's axis and the levers about it, as the bodies have moved and +# turned since the step began. +struct sliding { + var axis: vec2; + var perp: vec2; + var d: vec2; # From `a`'s anchor to `b`'s. + var ra: vec2; + var rb: vec2; + var a1: f32; # How each turns as the joint slides along its axis, + var a2: f32; + var s1: f32; # and across it. + var s2: f32; +} + +def sliding_of(r: &joint_record, sa: &body_state, sb: &body_state): sliding { + val ra := sa.dq.apply(r.ra); + val rb := sb.dq.apply(r.rb); + val d := (sb.dp - sa.dp) + r.delta_center + rb - ra; + val axis := sa.dq.apply(r.axis); + val perp := axis.perpendicular(); + return sliding{ + axis = axis, perp = perp, d = d, ra = ra, rb = rb, + a1 = (d + ra).cross(axis), a2 = rb.cross(axis), s1 = (d + ra).cross(perp), s2 = rb.cross(perp), + }; +} + +# Pushes the two apart by an impulse along a sliding joint and turns them by +# what it turns each. +def slide_apart(r: &joint_record, sa: &mut body_state, sb: &mut body_state, p: vec2, turn_a: f32, turn_b: f32): void { + sa.v = sa.v - p * r.ma; + sa.w -= r.ia * turn_a; + sb.v = sb.v + p * r.mb; + sb.w += r.ib * turn_b; +} + +def warm_sliding(r: &joint_record, sa: &mut body_state, sb: &mut body_state): void { + val g := sliding_of(r, sa, sb); + if r.made.kind == joint_kind::prismatic { + val axial := r.spring_impulse + r.motor_impulse + r.lower_impulse - r.upper_impulse; + val p := g.axis * axial + g.perp * r.linear.x; + slide_apart(r, sa, sb, p, axial * g.a1 + r.linear.x * g.s1 + r.linear.y, axial * g.a2 + r.linear.x * g.s2 + r.linear.y); + } else { + val axial := r.spring_impulse + r.lower_impulse - r.upper_impulse; + val p := g.axis * axial + g.perp * r.axial; + slide_apart(r, sa, sb, p, axial * g.a1 + r.axial * g.s1 + r.motor_impulse, axial * g.a2 + r.axial * g.s2 + r.motor_impulse); + } +} + +# How fast a sliding joint slides along its axis. +def sliding_speed(g: &sliding, sa: &body_state, sb: &body_state): f32 { + return g.axis.dot(sb.v - sa.v) + g.a2 * sb.w - g.a1 * sa.w; +} + +def solve_sliding(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, soft: &softness, h: f32, use_bias: bool): void { + val made := &r.made; + val g := sliding_of(r, sa, sb); + val translation := g.axis.dot(g.d); + if made.motor { + val most := h * made.max_motor_force; + val held := r.motor_impulse; + if made.kind == joint_kind::prismatic { + r.motor_impulse = math::clamp(held + r.axial_mass * (made.motor_speed - sliding_speed(&g, sa, sb)), -most, most); + val impulse := r.motor_impulse - held; + slide_apart(r, sa, sb, g.axis * impulse, impulse * g.a1, impulse * g.a2); + } else { + # A wheel's motor turns it. + r.motor_impulse = math::clamp(held - r.motor_mass * (sb.w - sa.w - made.motor_speed), -most, most); + turn_apart(r, sa, sb, r.motor_impulse - held); + } + } + if made.spring && made.hertz > 0 { + val bias := r.spring_soft.bias_rate * translation; + val impulse := -r.spring_soft.mass_scale * r.axial_mass * (sliding_speed(&g, sa, sb) + bias) - r.spring_soft.impulse_scale * r.spring_impulse; + r.spring_impulse += impulse; + slide_apart(r, sa, sb, g.axis * impulse, impulse * g.a1, impulse * g.a2); + } + if made.limit { + val lower := limit_impulse(translation - made.lower, sliding_speed(&g, sa, sb), r.axial_mass, r.lower_impulse, soft, 1 / h, use_bias); + r.lower_impulse += lower; + slide_apart(r, sa, sb, g.axis * lower, lower * g.a1, lower * g.a2); + val upper := limit_impulse(made.upper - translation, -sliding_speed(&g, sa, sb), r.axial_mass, r.upper_impulse, soft, 1 / h, use_bias); + r.upper_impulse += upper; + slide_apart(r, sa, sb, g.axis * -upper, -upper * g.a1, -upper * g.a2); + } + var bias_scale: f32 = 0; + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if use_bias { + bias_scale = soft.bias_rate; + mass_scale = soft.mass_scale; + impulse_scale = soft.impulse_scale; + } + val across := g.perp.dot(sb.v - sa.v) + g.s2 * sb.w - g.s1 * sa.w; + val k11 := r.ma + r.mb + r.ia * g.s1 * g.s1 + r.ib * g.s2 * g.s2; + if made.kind == joint_kind::wheel { + # Held to its axis alone, the wheel turning as it likes. + val held := r.axial; + val impulse := k11 > 0 ? -mass_scale * (across + bias_scale * g.perp.dot(g.d)) / k11 - impulse_scale * held : 0f; + r.axial = held + impulse; + slide_apart(r, sa, sb, g.perp * impulse, impulse * g.s1, impulse * g.s2); + return; + } + # Held to its axis and turning together, both at once. + val k12 := r.ia * g.s1 + r.ib * g.s2; + var k22 := r.ia + r.ib; + if k22 == 0 { + k22 = 1; + } + val turned_by := unwound(r.delta_angle + angle_between(sb.dq, sa.dq)); + val c := vec2{ across + bias_scale * g.perp.dot(g.d), sb.w - sa.w + bias_scale * turned_by }; + val b := solved(k11, k12, k12, k22, c); + val impulse := vec2{ -mass_scale * b.x - impulse_scale * r.linear.x, -mass_scale * b.y - impulse_scale * r.linear.y }; + r.linear = r.linear + impulse; + slide_apart(r, sa, sb, g.perp * impulse.x, impulse.x * g.s1 + impulse.y, impulse.x * g.s2 + impulse.y); +} + +# A motor joint: its turn driven toward its angle, then its place, each by no +# more than its share of its torque or force this substep. +def solve_motor(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, h: f32): void { + val made := &r.made; + val inv_h := 1 / h; + val turned_by := unwound(r.delta_angle + angle_between(sb.dq, sa.dq)); + val most_turn := h * made.max_motor_torque; + val turn_held := r.axial; + r.axial = math::clamp(turn_held - r.motor_mass * (sb.w - sa.w + inv_h * made.correction * turned_by), -most_turn, most_turn); + turn_apart(r, sa, sb, r.axial - turn_held); + val ra := sa.dq.apply(r.ra); + val rb := sb.dq.apply(r.rb); + val off := (sb.dp - sa.dp) + (rb - ra) + r.delta_center; + val cdot := sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, ra); + val k11 := r.ma + r.mb + ra.y * ra.y * r.ia + rb.y * rb.y * r.ib; + val k12 := -ra.y * ra.x * r.ia - rb.y * rb.x * r.ib; + val k22 := r.ma + r.mb + ra.x * ra.x * r.ia + rb.x * rb.x * r.ib; + val b := solved(k11, k12, k12, k22, cdot + off * (inv_h * made.correction)); + push_capped(r, sa, sb, ra, rb, b * -1f, h * made.max_motor_force); +} + +# A mouse joint: a place of `b` pulled softly toward its target. +def solve_mouse(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, h: f32): void { + val ra := sa.dq.apply(r.ra); + val rb := sb.dq.apply(r.rb); + val off := (sb.dp - sa.dp) + (rb - ra) + r.delta_center; + val cdot := sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, ra); + val soft := &r.linear_soft; + val k11 := r.ma + r.mb + ra.y * ra.y * r.ia + rb.y * rb.y * r.ib; + val k12 := -ra.y * ra.x * r.ia - rb.y * rb.x * r.ib; + val k22 := r.ma + r.mb + ra.x * ra.x * r.ia + rb.x * rb.x * r.ib; + val b := solved(k11, k12, k12, k22, cdot + off * soft.bias_rate); + val impulse := b * -soft.mass_scale - r.linear * soft.impulse_scale; + push_capped(r, sa, sb, ra, rb, impulse, h * r.made.max_motor_force); +} + +# Adds an impulse to a joint's at its anchors, its sum no longer than `most`. +def push_capped(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ra: vec2, rb: vec2, impulse: vec2, most: f32): void { + val held := r.linear; + var sum := held + impulse; + val length := sum.length; + if length > most { + sum = sum * (most / length); + } + r.linear = sum; + push_apart(r, sa, sb, ra, rb, sum - held); +} diff --git a/physics2d/grid.sakura b/physics2d/grid.sakura new file mode 100644 index 0000000..abeeb3f --- /dev/null +++ b/physics2d/grid.sakura @@ -0,0 +1,196 @@ +#! Contains `grid`: solid cells of a grid, as a tilemap's walls are, each a box +#! of the grid's cell size, from the grid's origin at the bottom left of its +#! first cell, x to the right and y up. +#! +#! A shape meets each solid cell as a box, but for the faces two solid cells +#! share: a manifold pushing the shape into a solid neighbor, along the axis +#! it pushes most, is passed over, so a body sliding along a floor of many +#! cells slides as along one, never caught on the seams between them. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics2d; + +#! Solid cells of a grid, so many across and up. +pub struct grid { + #! How wide and high each cell is. + pub var cell := vec2{ 1, 1 }; + var _width: u32; + var _height: u32; + var _solid: vector; # Each cell, a row at a time, from the bottom left. +} + +#! A grid so many cells across and up, each so wide and high, none solid. +pub def grid::new(width: u32, height: u32, cell: vec2 = vec2{ 1, 1 }): grid { + var made := grid{ cell = cell, _width = width, _height = height, _solid = vector::::new() }; + made._solid.resize(width as u64 * height as u64, 0); + return made; +} + +pub val grid::width: u32 { + get => this._width; +} + +pub val grid::height: u32 { + get => this._height; +} + +#! Whether a cell is solid: none outside the grid is. +pub def grid::is_solid(&this, x: i64, y: i64): bool { + return false if x < 0 || y < 0 || x >= this._width as i64 || y >= this._height as i64; + return this._solid[(y as u64) * this._width as u64 + x as u64] != 0; +} + +#! Makes a cell solid, or not. +pub def grid::set(&mut this, x: u32, y: u32, solid: bool): void { + return if x >= this._width || y >= this._height; + this._solid[y as u64 * this._width as u64 + x as u64] = solid ? 1 : 0; +} + +#! A cell's box, of the grid's own places. +pub def grid::box_of(&this, x: u32, y: u32): aabb { + val low := vec2{ x as f32 * this.cell.x, y as f32 * this.cell.y }; + return aabb{ low, low + this.cell }; +} + +#! The box of all its cells, of its own places. +pub val grid::bounds: aabb { + get => aabb{ vec2::zero, vec2{ this._width as f32 * this.cell.x, this._height as f32 * this.cell.y } }; +} + +#! Visits each solid cell a box of the grid's own places meets, as +#! `visit(x, y)`, until it gives false. +pub def grid::cells_in(&this, box: aabb, visit: F): void where F: invokable { + return if this._width == 0 || this._height == 0; + val x0 := math::max(math::floor(box.min.x / this.cell.x) as i64, 0); + val y0 := math::max(math::floor(box.min.y / this.cell.y) as i64, 0); + val x1 := math::min(math::floor(box.max.x / this.cell.x) as i64, this._width as i64 - 1); + val y1 := math::min(math::floor(box.max.y / this.cell.y) as i64, this._height as i64 - 1); + var y := y0; + while y <= y1 { + var x := x0; + while x <= x1 { + if this.is_solid(x, y) { + return if !visit(x as u32, y as u32); + } + x++; + } + y++; + } +} + +#! Visits the manifold of a shape against each solid cell it meets, as +#! `visit(x, y, m)`, until it gives false: `at` places the grid, and `at_s` +#! the shape, and each manifold's normal is from the cell toward the shape, +#! of the plane's places. Those pushing the shape into a solid neighbor are +#! passed over. Cells apart from the shape by no more than a margin are met +#! too, as `collide` meets them. +pub def grid::collide(&this, at: pose, s: &shape, at_s: pose, visit: F, margin: f32 = 0): void + where F: invokable { + val local := at.unapply_pose(at_s); + val half := this.cell * 0.5; + this.cells_in(s.bounds(local).grown(margin), def(x: u32, y: u32): bool { + val box := shape::box(half, vec2{ (x as f32 + 0.5) * this.cell.x, (y as f32 + 0.5) * this.cell.y }); + val found := collide(&box, pose::identity, s, local, margin) else { return true; }; + # Along the axis it pushes most, toward a solid neighbor, it's a face the + # two share. + val n := found.normal; + var nx: i64 = 0; + var ny: i64 = 0; + if math::abs(n.x) > math::abs(n.y) { + nx = n.x > 0 ? 1 : -1; + } else { + ny = n.y > 0 ? 1 : -1; + } + return true if this.is_solid(x as i64 + nx, y as i64 + ny); + var placed := manifold{ normal = at.turn.apply(n), count = found.count }; + for i in 0..found.count { + placed.points[i] = contact{ point = at.apply(found.points[i].point), depth = found.points[i].depth, id = found.points[i].id }; + } + return visit(x, y, placed); + }); +} + +#! Whether a shape meets any solid cell, `at` placing the grid and `at_s` the +#! shape, but where it only meets the faces solid cells share. +pub def grid::overlaps(&this, at: pose, s: &shape, at_s: pose): bool { + var met := false; + this.collide(at, s, at_s, def(x: u32, y: u32, m: manifold): bool { + met = true; + return false; + }); + return met; +} + +#! Where a ray met a grid: the hit, and the solid cell it met. +pub struct grid_hit { + pub var hit: ray_hit; + pub var x: u32; + pub var y: u32; +} + +#! Where a ray first meets a solid cell, `at` placing the grid: from a place, +#! along a direction of length 1, as far as `reach`, passing from cell to cell +#! as Amanatides and Woo pass, the face it enters by its normal. A ray +#! beginning in a solid cell meets it at 0, facing back along the ray. +pub def grid::ray_cast(&this, at: pose, origin: vec2, direction: vec2, reach: f32): maybe { + val o := at.unapply(origin); + val d := at.turn.unapply(direction); + val whole := this.bounds; + val start := whole.ray_hit(o, d, reach) else { return nothing{}; }; + val p := o + d * start; + var x := math::clamp(math::floor(p.x / this.cell.x) as i64, 0, this._width as i64 - 1); + var y := math::clamp(math::floor(p.y / this.cell.y) as i64, 0, this._height as i64 - 1); + # The face of the grid it entered by, or none where it began within it. + var normal := d * -1f; + if start > 0 { + val gaps: f32[4] = [math::abs(p.x - whole.min.x), math::abs(p.x - whole.max.x), math::abs(p.y - whole.min.y), math::abs(p.y - whole.max.y)]; + val faces: vec2[4] = [vec2{ -1, 0 }, vec2{ 1, 0 }, vec2{ 0, -1 }, vec2{ 0, 1 }]; + var nearest: u64 = 0; + for i in 1..4u { + if gaps[i] < gaps[nearest] { + nearest = i; + } + } + normal = faces[nearest]; + } + val step_x: i64 = d.x > 0 ? 1 : d.x < 0 ? -1 : 0; + val step_y: i64 = d.y > 0 ? 1 : d.y < 0 ? -1 : 0; + val across_x := step_x != 0 ? this.cell.x / math::abs(d.x) : 1e30f; + val across_y := step_y != 0 ? this.cell.y / math::abs(d.y) : 1e30f; + # How far along the ray, from its beginning, each next line of cells is. + var next_x := 1e30f; + var next_y := 1e30f; + if step_x > 0 { + next_x = ((x + 1) as f32 * this.cell.x - o.x) / d.x; + } else if step_x < 0 { + next_x = (x as f32 * this.cell.x - o.x) / d.x; + } + if step_y > 0 { + next_y = ((y + 1) as f32 * this.cell.y - o.y) / d.y; + } else if step_y < 0 { + next_y = (y as f32 * this.cell.y - o.y) / d.y; + } + var t := start; + while true { + if this.is_solid(x, y) { + return grid_hit{ + hit = ray_hit{ distance = t, point = at.apply(o + d * t), normal = at.turn.apply(normal) }, x = x as u32, y = y as u32, + }; + } + if next_x < next_y { + t = next_x; + next_x += across_x; + x += step_x; + normal = vec2{ -step_x as f32, 0 }; + } else { + t = next_y; + next_y += across_y; + y += step_y; + normal = vec2{ 0, -step_y as f32 }; + } + return nothing{} if t > reach || x < 0 || y < 0 || x >= this._width as i64 || y >= this._height as i64; + } + return nothing{}; +} diff --git a/physics2d/joint_solver.sakura b/physics2d/joint_solver.sakura new file mode 100644 index 0000000..6c9a8b5 --- /dev/null +++ b/physics2d/joint_solver.sakura @@ -0,0 +1,289 @@ +#! Contains how a step solves joints, as Box2D's soft step solves them: each +#! is prepared as the step begins, begins each substep with the impulses it +#! ended the last with, and pushes its bodies' velocities toward holding it, +#! undoing drift softly where `use_bias` asks. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics2d; + +def space::prepare_joints(&mut this, s: &mut solver_scratch, h: f32): void { + s.joints.clear(); + s.joint_soft = soft_of(this.joint_hertz, this.joint_damping, h); + for j in 0..this.joints.length { + continue if !this.joints[j].alive; + var r := this.joints[j]; + val a := &this.bodies[r.body_a as u64]; + val b := &this.bodies[r.body_b as u64]; + continue if a.slot == 0 && b.slot == 0; + s.joints.append(j as u32); + r.slot_a = a.slot; + r.slot_b = b.slot; + r.ma = a.inv_mass; + r.ia = a.inv_inertia; + r.mb = b.inv_mass; + r.ib = b.inv_inertia; + r.ra = a.at.turn.apply(r.made.anchor_a - a.local_center); + r.rb = b.at.turn.apply(r.made.anchor_b - b.local_center); + r.delta_center = b.center - a.center; + r.delta_angle = unwound(angle_between(b.at.turn, a.at.turn) - r.made.reference_angle); + var k := r.ia + r.ib; + if r.made.kind == joint_kind::revolute { + # A pin turns each body about itself, not about its center, as the + # point it's held at keeps it: how hard that is is its inertia, and its + # mass as far from the pin as its center is, so a limit stops a door + # outright rather than leaving the point to turn it back. + k = about_pin(a, r.ra) + about_pin(b, r.rb); + } + r.axial_mass = k > 0 ? 1 / k : 0f; + if r.made.kind == joint_kind::distance { + val axis := (r.rb - r.ra + r.delta_center).normalized(); + val cra := r.ra.cross(axis); + val crb := r.rb.cross(axis); + val kd := r.ma + r.mb + r.ia * cra * cra + r.ib * crb * crb; + r.axial_mass = kd > 0 ? 1 / kd : 0f; + } + if r.made.kind == joint_kind::prismatic || r.made.kind == joint_kind::wheel { + r.axis = a.at.turn.apply(r.made.axis.normalized()); + val d := r.delta_center + r.rb - r.ra; + val a1 := (d + r.ra).cross(r.axis); + val a2 := r.rb.cross(r.axis); + val ks := r.ma + r.mb + r.ia * a1 * a1 + r.ib * a2 * a2; + r.axial_mass = ks > 0 ? 1 / ks : 0f; + } + val turning := r.ia + r.ib; + r.motor_mass = turning > 0 ? 1 / turning : 0f; + r.spring_soft = soft_of(r.made.hertz, r.made.damping, h); + r.linear_soft = r.made.hertz == 0 ? s.joint_soft : soft_of(r.made.hertz, r.made.damping, h); + r.angular_soft = r.made.angular_hertz == 0 ? s.joint_soft : soft_of(r.made.angular_hertz, r.made.angular_damping, h); + this.joints[j] = r; + } +} + +# How easily a body turns about a place `r` from its center: the inverse of +# its inertia about it. +def about_pin(b: &body_record, r: vec2): f32 { + return 0 if b.inv_mass == 0 || b.inv_inertia == 0; + return 1 / (b.inertia + b.mass * r.length_squared); +} + +def space::warm_joints(&mut this, s: &mut solver_scratch): void { + for i in 0..s.joints.length { + val r := &this.joints[s.joints[i] as u64]; + var sa := s.states[r.slot_a as u64]; + var sb := s.states[r.slot_b as u64]; + val ra := sa.dq.apply(r.ra); + val rb := sb.dq.apply(r.rb); + var p := vec2::zero; + var turn: f32 = 0; + if r.made.kind == joint_kind::prismatic || r.made.kind == joint_kind::wheel { + warm_sliding(r, &mut sa, &mut sb); + } else if r.made.kind == joint_kind::motor || r.made.kind == joint_kind::mouse { + p = r.linear; + turn = r.axial; + } else if r.made.kind == joint_kind::revolute { + p = r.linear; + turn = r.spring_impulse + r.motor_impulse + r.lower_impulse - r.upper_impulse; + } else if r.made.kind == joint_kind::weld { + p = r.linear; + turn = r.axial; + } else { + val axis := ((sb.dp - sa.dp) + r.delta_center + (rb - ra)).normalized(); + p = axis * (r.axial + r.spring_impulse + r.lower_impulse - r.upper_impulse + r.motor_impulse); + } + sa.v = sa.v - p * r.ma; + sa.w -= r.ia * (ra.cross(p) + turn); + sb.v = sb.v + p * r.mb; + sb.w += r.ib * (rb.cross(p) + turn); + s.states[r.slot_a as u64].v = sa.v; + s.states[r.slot_a as u64].w = sa.w; + s.states[r.slot_b as u64].v = sb.v; + s.states[r.slot_b as u64].w = sb.w; + } +} + +def space::solve_joints(&mut this, s: &mut solver_scratch, h: f32, use_bias: bool): void { + for i in 0..s.joints.length { + val j := s.joints[i] as u64; + var r := this.joints[j]; + var sa := s.states[r.slot_a as u64]; + var sb := s.states[r.slot_b as u64]; + if r.made.kind == joint_kind::revolute { + solve_revolute(&mut r, &mut sa, &mut sb, &s.joint_soft, h, use_bias); + } else if r.made.kind == joint_kind::prismatic || r.made.kind == joint_kind::wheel { + solve_sliding(&mut r, &mut sa, &mut sb, &s.joint_soft, h, use_bias); + } else if r.made.kind == joint_kind::motor { + solve_motor(&mut r, &mut sa, &mut sb, h); + } else if r.made.kind == joint_kind::mouse { + solve_mouse(&mut r, &mut sa, &mut sb, h); + } else if r.made.kind == joint_kind::weld { + solve_weld(&mut r, &mut sa, &mut sb, use_bias); + } else { + solve_distance(&mut r, &mut sa, &mut sb, &s.joint_soft, h, use_bias); + } + this.joints[j] = r; + s.states[r.slot_a as u64].v = sa.v; + s.states[r.slot_a as u64].w = sa.w; + s.states[r.slot_b as u64].v = sb.v; + s.states[r.slot_b as u64].w = sb.w; + } +} + +# Turns the two apart by an angular impulse. +def turn_apart(r: &joint_record, sa: &mut body_state, sb: &mut body_state, impulse: f32): void { + sa.w -= r.ia * impulse; + sb.w += r.ib * impulse; +} + +# Pushes the two apart by an impulse at their anchors. +def push_apart(r: &joint_record, sa: &mut body_state, sb: &mut body_state, ra: vec2, rb: vec2, p: vec2): void { + sa.v = sa.v - p * r.ma; + sa.w -= r.ia * ra.cross(p); + sb.v = sb.v + p * r.mb; + sb.w += r.ib * rb.cross(p); +} + +# A one-sided limit's impulse, as a contact's: of `c` how far it is from +# closing, and `cdot` how fast it closes. +def limit_impulse(c: f32, cdot: f32, mass: f32, held: f32, soft: &softness, inv_h: f32, use_bias: bool): f32 { + var bias: f32 = 0; + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if c > 0 { + bias = c * inv_h; + } else if use_bias { + bias = soft.bias_rate * c; + mass_scale = soft.mass_scale; + impulse_scale = soft.impulse_scale; + } + val impulse := -mass * mass_scale * (cdot + bias) - impulse_scale * held; + return math::max(held + impulse, 0f) - held; +} + +def solve_revolute(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, soft: &softness, h: f32, use_bias: bool): void { + val made := &r.made; + val turned_by := unwound(r.delta_angle + angle_between(sb.dq, sa.dq)); + if made.spring && made.hertz > 0 { + val bias := r.spring_soft.bias_rate * turned_by; + val impulse := -r.spring_soft.mass_scale * r.axial_mass * (sb.w - sa.w + bias) - r.spring_soft.impulse_scale * r.spring_impulse; + r.spring_impulse += impulse; + turn_apart(r, sa, sb, impulse); + } + if made.motor { + val most := h * made.max_motor_force; + val held := r.motor_impulse; + r.motor_impulse = math::clamp(held - r.axial_mass * (sb.w - sa.w - made.motor_speed), -most, most); + turn_apart(r, sa, sb, r.motor_impulse - held); + } + if made.limit { + val lower := limit_impulse(turned_by - made.lower, sb.w - sa.w, r.axial_mass, r.lower_impulse, soft, 1 / h, use_bias); + r.lower_impulse += lower; + turn_apart(r, sa, sb, lower); + val upper := limit_impulse(made.upper - turned_by, sa.w - sb.w, r.axial_mass, r.upper_impulse, soft, 1 / h, use_bias); + r.upper_impulse += upper; + turn_apart(r, sa, sb, -upper); + } + # The anchors held at one point. + val ra := sa.dq.apply(r.ra); + val rb := sb.dq.apply(r.rb); + val cdot := sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, ra); + var bias := vec2::zero; + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if use_bias { + bias = ((sb.dp - sa.dp) + (rb - ra) + r.delta_center) * soft.bias_rate; + mass_scale = soft.mass_scale; + impulse_scale = soft.impulse_scale; + } + val k11 := r.ma + r.mb + ra.y * ra.y * r.ia + rb.y * rb.y * r.ib; + val k12 := -ra.y * ra.x * r.ia - rb.y * rb.x * r.ib; + val k22 := r.ma + r.mb + ra.x * ra.x * r.ia + rb.x * rb.x * r.ib; + val b := solved(k11, k12, k12, k22, cdot + bias); + val impulse := vec2{ -mass_scale * b.x - impulse_scale * r.linear.x, -mass_scale * b.y - impulse_scale * r.linear.y }; + r.linear = r.linear + impulse; + push_apart(r, sa, sb, ra, rb, impulse); +} + +def solve_weld(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, use_bias: bool): void { + # Their turn held. + var bias: f32 = 0; + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if use_bias || r.made.angular_hertz > 0 { + bias = r.angular_soft.bias_rate * unwound(angle_between(sb.dq, sa.dq) + r.delta_angle); + mass_scale = r.angular_soft.mass_scale; + impulse_scale = r.angular_soft.impulse_scale; + } + val turn := -r.axial_mass * mass_scale * (sb.w - sa.w + bias) - impulse_scale * r.axial; + r.axial += turn; + turn_apart(r, sa, sb, turn); + # Their anchors held at one point. + val ra := sa.dq.apply(r.ra); + val rb := sb.dq.apply(r.rb); + var place := vec2::zero; + mass_scale = 1; + impulse_scale = 0; + if use_bias || r.made.hertz > 0 { + place = ((sb.dp - sa.dp) + (rb - ra) + r.delta_center) * r.linear_soft.bias_rate; + mass_scale = r.linear_soft.mass_scale; + impulse_scale = r.linear_soft.impulse_scale; + } + val cdot := sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, ra); + val k11 := r.ma + r.mb + ra.y * ra.y * r.ia + rb.y * rb.y * r.ib; + val k12 := -ra.y * ra.x * r.ia - rb.y * rb.x * r.ib; + val k22 := r.ma + r.mb + ra.x * ra.x * r.ia + rb.x * rb.x * r.ib; + val b := solved(k11, k12, k12, k22, cdot + place); + val impulse := vec2{ -mass_scale * b.x - impulse_scale * r.linear.x, -mass_scale * b.y - impulse_scale * r.linear.y }; + r.linear = r.linear + impulse; + push_apart(r, sa, sb, ra, rb, impulse); +} + +def solve_distance(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, soft: &softness, h: f32, use_bias: bool): void { + val made := &r.made; + val ra := sa.dq.apply(r.ra); + val rb := sb.dq.apply(r.rb); + val d := (sb.dp - sa.dp) + r.delta_center + (rb - ra); + val length := d.length; + val axis := d.normalized(); + # Soft where it springs between its limits; else a rod. + if made.spring && (!made.limit || made.lower < made.upper) { + if made.hertz > 0 { + val cdot := axis.dot(sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, ra)); + val bias := r.spring_soft.bias_rate * (length - made.length); + val impulse := -r.spring_soft.mass_scale * r.axial_mass * (cdot + bias) - r.spring_soft.impulse_scale * r.spring_impulse; + r.spring_impulse += impulse; + push_apart(r, sa, sb, ra, rb, axis * impulse); + } + } else { + val cdot := axis.dot(sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, ra)); + var bias: f32 = 0; + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if use_bias { + bias = soft.bias_rate * (length - made.length); + mass_scale = soft.mass_scale; + impulse_scale = soft.impulse_scale; + } + val impulse := -mass_scale * r.axial_mass * (cdot + bias) - impulse_scale * r.axial; + r.axial += impulse; + push_apart(r, sa, sb, ra, rb, axis * impulse); + } + if made.limit && made.lower < made.upper { + val closing := axis.dot(sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, ra)); + val lower := limit_impulse(length - made.lower, closing, r.axial_mass, r.lower_impulse, soft, 1 / h, use_bias); + r.lower_impulse += lower; + push_apart(r, sa, sb, ra, rb, axis * lower); + val opening := axis.dot(sa.v + spun(sa.w, ra) - sb.v - spun(sb.w, rb)); + val upper := limit_impulse(made.upper - length, opening, r.axial_mass, r.upper_impulse, soft, 1 / h, use_bias); + r.upper_impulse += upper; + push_apart(r, sa, sb, ra, rb, axis * -upper); + } + if made.motor { + val most := h * made.max_motor_force; + val held := r.motor_impulse; + val cdot := axis.dot(sb.v + spun(sb.w, rb) - sa.v - spun(sa.w, ra)); + r.motor_impulse = math::clamp(held + r.axial_mass * (made.motor_speed - cdot), -most, most); + push_apart(r, sa, sb, ra, rb, axis * (r.motor_impulse - held)); + } +} diff --git a/physics2d/joints.sakura b/physics2d/joints.sakura new file mode 100644 index 0000000..97a35c6 --- /dev/null +++ b/physics2d/joints.sakura @@ -0,0 +1,435 @@ +#! Contains joints, which hold two bodies together: a `revolute` joint pins +#! them at a point they turn about, as a hinge or an axle, with limits to how +#! far it turns and a motor to turn it; a `distance` joint keeps two points +#! apart, rigidly as a rod, within lengths as a rope, or springily; and a +#! `weld` holds them as one body, rigidly or springily. +#! +#! Joints are solved before contacts in each substep, as Box2D's are, softly +#! as contacts are: each undoes what has drifted as a stiff, damped spring of +#! the space's joint frequency, and a limit pushes only as far as closes it +#! this substep where it's apart, as a speculative contact does. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics2d; + +#! What a joint holds. +pub enum joint_kind: u8 { + #! The two at a point, about which they turn, as a hinge. + revolute, + #! Two points apart, as a rod, a rope, or a spring. + distance, + #! The two as one. + weld, + #! The two sliding along an axis, turning together, as a piston or a drawer. + prismatic, + #! The two along an axis, springily, turning as they like, as a car's wheel + #! on its suspension. + wheel, + #! `b` driven toward a place and an angle of `a`'s own, by no more than so + #! much force and torque, as a character steered or a door shut. + motor, + #! `b` pulled by a spring toward a target, as a mouse drags it. + mouse, +} + +#! What a joint is made as: its kind, its bodies, where it holds each, of the +#! body's own places, and what each kind asks. +pub struct joint { + pub var kind := joint_kind::revolute; + pub var a: body_id; + pub var b: body_id; + #! Where it holds each, of the body's own places: of a motor joint, where it + #! drives `b`'s origin to, of `a`'s, and of a mouse joint, its target. + pub var anchor_a: vec2; + pub var anchor_b: vec2; + #! Of a prismatic or wheel joint, the axis it slides along, of `a`'s own + #! directions. + pub var axis := vec2{ 1, 0 }; + #! Whether the two bodies still meet where their colliders do. + pub var collide: bool; + #! Of a revolute, prismatic, or motor joint or a weld, how far `b` is + #! turned from `a`, in radians, where it rests, or is driven to. + pub var reference_angle: f32; + #! Whether it's limited: a revolute joint to turning from `lower` to + #! `upper` radians from its reference, a distance joint to lengths between + #! them, and a prismatic or wheel joint to sliding between them along its + #! axis, from where its anchors meet. + pub var limit: bool; + pub var lower: f32; + pub var upper: f32; + #! A motor turning a revolute or wheel joint at a speed, in radians a + #! second, or lengthening a distance joint or sliding a prismatic one, in + #! lengths a second, with no more than so much torque or force. Of a motor + #! or mouse joint, the most force it drives `b` with. + pub var motor: bool; + pub var motor_speed: f32; + pub var max_motor_force: f32; + #! Of a motor joint, the most torque it turns `b` with, and how much of + #! what's left to drive it undoes each step. + pub var max_motor_torque: f32; + pub var correction: f32 = 0.3; + #! A spring toward a revolute joint's reference angle, a distance joint's + #! length, or where a prismatic or wheel joint's anchors meet, of so many + #! cycles a second, damped so: 1 doesn't spring back. Of a weld, how stiff it + #! holds its place, 0 rigid, and of a mouse joint, how stiff it pulls. + pub var spring: bool; + pub var hertz: f32; + pub var damping: f32 = 1; + #! Of a distance joint, the length it holds. + pub var length: f32 = 1; + #! Of a weld, how stiff it holds its turn, 0 rigid. + pub var angular_hertz: f32; + pub var angular_damping: f32 = 1; + #! A number of its user's. + pub var data: u64; +} + +#! A joint of a space, as `space::join` names it. +pub struct joint_id { + pub var index: u32 = 0xFFFFFFFF; + pub var generation: u32; +} + +pub def joint_id::equals(&this, other: &joint_id): bool { + return this.index == other.index && this.generation == other.generation; +} + +# A joint as the space keeps it, and what a step works out of it. +struct joint_record { + var made: joint; + var generation: u32; + var alive: bool; + var body_a: u32; + var body_b: u32; + var next_a: u32 = 0xFFFFFFFF; # The next joint of each body. + var next_b: u32 = 0xFFFFFFFF; + var slot_a: u32; + var slot_b: u32; + var ma: f32; + var ia: f32; + var mb: f32; + var ib: f32; + var ra: vec2; # Each anchor from its body's center, as the step began. + var rb: vec2; + var delta_center: vec2; + var delta_angle: f32; + var axis: vec2; # Of a prismatic or wheel joint, as `a` was turned as the step began. + var axial_mass: f32; + var motor_mass: f32; + var linear: vec2; # Impulses, kept from step to step. + var axial: f32; + var spring_impulse: f32; + var motor_impulse: f32; + var lower_impulse: f32; + var upper_impulse: f32; + var spring_soft: softness; + var linear_soft: softness; + var angular_soft: softness; +} + +#! Joins two bodies. +pub def space::join(&mut this, made: joint): joint_id { + return joint_id{} if !this.has(made.a) || !this.has(made.b) || made.a.index == made.b.index; + var index: u32 = 0; + if this.free_joints.length > 0 { + index = this.free_joints[this.free_joints.length - 1]; + this.free_joints.truncate(); + } else { + index = this.joints.length as u32; + this.joints.append(joint_record{}); + } + val generation := this.joints[index as u64].generation + 1; + val a := made.a.index; + val b := made.b.index; + this.joints[index as u64] = joint_record{ + made = made, generation = generation, alive = true, body_a = a, body_b = b, + next_a = this.bodies[a as u64].joints, next_b = this.bodies[b as u64].joints, + }; + this.bodies[a as u64].joints = index; + this.bodies[b as u64].joints = index; + if !made.collide { + this.drop_pairs_between(a, b); + } + this.wake_body(a); + this.wake_body(b); + return joint_id{ index = index, generation = generation }; +} + +#! Pins two bodies at a place of the plane, about which they turn. +pub def space::pin(&mut this, a: body_id, b: body_id, at: vec2): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + val pa := this.pose_of(a); + val pb := this.pose_of(b); + return this.join(joint{ + kind = joint_kind::revolute, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at), + reference_angle = angle_between(pb.turn, pa.turn), + }); +} + +#! Keeps two places of the plane, one of each body, as far apart as they are. +pub def space::tie(&mut this, a: body_id, b: body_id, at_a: vec2, at_b: vec2): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + return this.join(joint{ + kind = joint_kind::distance, a = a, b = b, anchor_a = this.pose_of(a).unapply(at_a), anchor_b = this.pose_of(b).unapply(at_b), + length = (at_b - at_a).length, collide = true, + }); +} + +#! Holds two bodies together as one, about a place of the plane. +pub def space::weld(&mut this, a: body_id, b: body_id, at: vec2): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + val pa := this.pose_of(a); + val pb := this.pose_of(b); + return this.join(joint{ + kind = joint_kind::weld, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at), + reference_angle = angle_between(pb.turn, pa.turn), + }); +} + +#! Lets two bodies slide along an axis of the plane through a place, turning +#! together, as a piston: a prismatic joint, its limits and motor its own to +#! set. +pub def space::slide(&mut this, a: body_id, b: body_id, at: vec2, axis: vec2): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + val pa := this.pose_of(a); + val pb := this.pose_of(b); + return this.join(joint{ + kind = joint_kind::prismatic, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at), + axis = pa.turn.unapply(axis.normalized()), reference_angle = angle_between(pb.turn, pa.turn), + }); +} + +#! Holds a wheel, `b`, to a body, `a`, at a place of the plane, along an axis +#! it rides on springily, as a car's suspension: a spring of so many cycles a +#! second, damped so, and a motor to turn it its own to set. +pub def space::wheel(&mut this, a: body_id, b: body_id, at: vec2, axis: vec2, hertz: f32 = 4, damping: f32 = 0.7): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + val pa := this.pose_of(a); + return this.join(joint{ + kind = joint_kind::wheel, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = this.pose_of(b).unapply(at), + axis = pa.turn.unapply(axis.normalized()), spring = true, hertz = hertz, damping = damping, + }); +} + +#! Drives `b` to stay where it is of `a`, and turned as it is, by no more than +#! so much force and torque, as `space::drive_to` moves where: a motor joint. +pub def space::drive(&mut this, a: body_id, b: body_id, max_force: f32, max_torque: f32): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + val pa := this.pose_of(a); + val pb := this.pose_of(b); + return this.join(joint{ + kind = joint_kind::motor, a = a, b = b, anchor_a = pa.unapply(pb.at), reference_angle = angle_between(pb.turn, pa.turn), + max_motor_force = max_force, max_motor_torque = max_torque, collide = true, + }); +} + +#! Grabs a body at a place of the plane, pulling that place of it toward a +#! target by a spring of so many cycles a second, damped so, with no more than +#! so much force, as a mouse drags it: a mouse joint, held by `ground`, a body +#! standing still, its target moved by `space::drive_to`. +pub def space::grab(&mut this, ground: body_id, b: body_id, at: vec2, max_force: f32, hertz: f32 = 5, damping: f32 = 0.7): joint_id { + return joint_id{} if !this.has(ground) || !this.has(b); + return this.join(joint{ + kind = joint_kind::mouse, a = ground, b = b, anchor_a = this.pose_of(ground).unapply(at), anchor_b = this.pose_of(b).unapply(at), + max_motor_force = max_force, spring = true, hertz = hertz, damping = damping, collide = true, + }); +} + +#! Moves where a motor joint drives its body, a place of the plane, turned by an +#! angle from `a`, or a mouse joint's target, waking its bodies. +pub def space::drive_to(&mut this, id: joint_id, at: vec2, angle: f32 = 0): void { + return if !this.has(id); + val j := id.index as u64; + val a := this.joints[j].body_a; + this.joints[j].made.anchor_a = this.bodies[a as u64].at.unapply(at); + if this.joints[j].made.kind == joint_kind::motor { + this.joints[j].made.reference_angle = angle; + } + this.wake_body(a); + this.wake_body(this.joints[j].body_b); +} + +#! How far a prismatic or wheel joint has slid along its axis, from where its +#! anchors meet. +pub def space::translation_of(&this, id: joint_id): f32 { + return 0 if !this.has(id); + val j := &this.joints[id.index as u64]; + val pa := this.bodies[j.body_a as u64].at; + val pb := this.bodies[j.body_b as u64].at; + return (pb.apply(j.made.anchor_b) - pa.apply(j.made.anchor_a)).dot(pa.turn.apply(j.made.axis.normalized())); +} + +#! Whether a joint is of it still. +pub def space::has(&this, id: joint_id): bool { + return id.index < this.joints.length as u32 && this.joints[id.index as u64].alive && this.joints[id.index as u64].generation == id.generation; +} + +#! What a joint was made as, or last changed to. +pub def space::joint_of(&this, id: joint_id): &joint { + return &this.joints[id.index as u64].made; +} + +#! Changes what a joint asks, as its motor or limits, keeping its bodies and +#! anchors, and wakes them. What it no longer asks pushes no more: a motor, +#! limits, or a spring turned off. +pub def space::change(&mut this, id: joint_id, made: joint): void { + return if !this.has(id); + val j := id.index as u64; + val a := this.joints[j].made.a; + val b := this.joints[j].made.b; + if !made.motor { + this.joints[j].motor_impulse = 0; + } + if !made.limit { + this.joints[j].lower_impulse = 0; + this.joints[j].upper_impulse = 0; + } + if !made.spring { + this.joints[j].spring_impulse = 0; + } + this.joints[j].made = made; + this.joints[j].made.a = a; + this.joints[j].made.b = b; + this.wake_body(a.index); + this.wake_body(b.index); +} + +#! How far a revolute joint is turned from its reference, in radians. +pub def space::angle_of(&this, id: joint_id): f32 { + return 0 if !this.has(id); + val j := &this.joints[id.index as u64]; + return unwound(angle_between(this.bodies[j.body_b as u64].at.turn, this.bodies[j.body_a as u64].at.turn) - j.made.reference_angle); +} + +#! Takes a joint away, waking its bodies. +pub def space::unjoin(&mut this, id: joint_id): void { + return if !this.has(id); + this.drop_joint(id.index); +} + +def space::drop_joint(&mut this, j: u32): void { + val a := this.joints[j as u64].body_a; + val b := this.joints[j as u64].body_b; + this.unlink_joint(j, a); + this.unlink_joint(j, b); + this.joints[j as u64].alive = false; + this.free_joints.append(j); + this.wake_body(a); + this.wake_body(b); + # What it kept apart may meet again. + this.touch_colliders(a); +} + +# Takes a joint from a body's list of them. +def space::unlink_joint(&mut this, j: u32, body: u32): void { + val next := this.next_joint(j, body); + if this.bodies[body as u64].joints == j { + this.bodies[body as u64].joints = next; + return; + } + var k := this.bodies[body as u64].joints; + while k != none { + val after := this.next_joint(k, body); + if after == j { + if this.joints[k as u64].body_a == body { + this.joints[k as u64].next_a = next; + } else { + this.joints[k as u64].next_b = next; + } + return; + } + k = after; + } +} + +# The joint after another of a body's. +def space::next_joint(&this, j: u32, body: u32): u32 { + return this.joints[j as u64].body_a == body ? this.joints[j as u64].next_a : this.joints[j as u64].next_b; +} + +# Whether a joint holds two bodies and keeps them from meeting. +def space::joined_apart(&this, a: u32, b: u32): bool { + var j := this.bodies[a as u64].joints; + while j != none { + val joint := &this.joints[j as u64]; + val other := joint.body_a == a ? joint.body_b : joint.body_a; + return true if other == b && !joint.made.collide; + j = this.next_joint(j, a); + } + return false; +} + +def space::drop_joints_of(&mut this, b: u32): void { + while this.bodies[b as u64].joints != none { + this.drop_joint(this.bodies[b as u64].joints); + } +} + +# Drops the pairs of two bodies' colliders. +def space::drop_pairs_between(&mut this, a: u32, b: u32): void { + for p in 0..this.pairs.length { + continue if !this.pairs[p].alive; + val ba := this.colliders[this.pairs[p].a as u64].body; + val bb := this.colliders[this.pairs[p].b as u64].body; + if (ba == a && bb == b) || (ba == b && bb == a) { + this.drop_pair(p as u32, false); + } + } +} + +# Has a body's colliders find what they near again, as after a joint that +# kept them from meeting is gone. +def space::touch_colliders(&mut this, b: u32): void { + var c := this.bodies[b as u64].colliders; + while c != none { + if !this.colliders[c as u64].moved { + this.colliders[c as u64].moved = true; + this.moved.append(c); + } + c = this.colliders[c as u64].next; + } +} + +def space::join_jointed(&this, parent: &mut vector): void { + for j in 0..this.joints.length { + val joint := &this.joints[j]; + continue if !joint.alive; + if parent[joint.body_a as u64] != none && parent[joint.body_b as u64] != none { + join(parent, joint.body_a, joint.body_b); + } + } +} + +# How far `b` is turned past `a`, from -π to π. +def angle_between(b: rot, a: rot): f32 { + return math::atan2(b.s * a.c - b.c * a.s, b.c * a.c + b.s * a.s); +} + +# An angle brought within -π to π. +def unwound(angle: f32): f32 { + val pi := math::pi as f32; + return angle < -pi ? angle + 2 * pi : angle > pi ? angle - 2 * pi : angle; +} + +# What solves `[k11 k12; k21 k22] x = b`. +def solved(k11: f32, k12: f32, k21: f32, k22: f32, b: vec2): vec2 { + var det := k11 * k22 - k12 * k21; + if det != 0 { + det = 1 / det; + } + return vec2{ det * (k22 * b.x - k12 * b.y), det * (k11 * b.y - k21 * b.x) }; +} + +#! Visits each joint, as `visit(joint, at_a, at_b)`, where it holds each of its +#! bodies, of space's places, until it gives false, as gizmos draw them. +pub def space::each_joint(&this, visit: F): void where F: invokable { + for j in 0..this.joints.length { + val r := &this.joints[j]; + continue if !r.alive; + val at_a := this.bodies[r.body_a as u64].at.apply(r.made.anchor_a); + val at_b := this.bodies[r.body_b as u64].at.apply(r.made.anchor_b); + return if !visit(joint_id{ index = j as u32, generation = r.generation }, at_a, at_b); + } +} \ No newline at end of file diff --git a/physics2d/mass.sakura b/physics2d/mass.sakura new file mode 100644 index 0000000..99f7053 --- /dev/null +++ b/physics2d/mass.sakura @@ -0,0 +1,77 @@ +#! Contains `mass_data`: how heavy a shape is of a density, where its mass is +#! centered, and how hard it is to turn, as a body's colliders sum to it. + +import std::math; +import malunal::linear; +module malunal::physics2d; + +#! How heavy something is, where its mass is centered, of its body's own +#! places, and how hard it is to turn about that center: its rotational +#! inertia. +pub struct mass_data { + pub var mass: f32; + pub var center: vec2; + pub var inertia: f32; +} + +#! It and another together: their masses summed about their joint center. +pub def mass_data::add(&this, other: &mass_data): mass_data { + val mass := this.mass + other.mass; + return mass_data{ inertia = this.inertia + other.inertia } if mass <= 0; + val center := (this.center * this.mass + other.center * other.mass) * (1 / mass); + # Each turns about the joint center as about its own, and as far as it's + # from it, as the parallel axis theorem finds. + val inertia := this.inertia + this.mass * (this.center - center).length_squared + + other.inertia + other.mass * (other.center - center).length_squared; + return mass_data{ mass = mass, center = center, inertia = inertia }; +} + +#! Its mass of a density, a mass for each area of 1. +pub def shape::mass(&this, density: f32): mass_data { + if this.kind == shape_kind::circle { + val rr := this.radius * this.radius; + val mass := density * math::pi as f32 * rr; + return mass_data{ mass = mass, center = this.point(0), inertia = mass * rr * 0.5 }; + } + if this.kind == shape_kind::capsule { + return capsule_mass(this.point(0), this.point(1), this.radius, density); + } + return polygon_mass(this, density); +} + +# A capsule's: a box between its ends, and a circle of its two round halves, +# each half's own center 4r/3π past the box's end, as Box2D finds it. +def capsule_mass(p1: vec2, p2: vec2, radius: f32, density: f32): mass_data { + val rr := radius * radius; + val length := (p2 - p1).length; + val circle := density * math::pi as f32 * rr; + val box := density * 2 * radius * length; + val half := length * 0.5; + val off := 4 * radius / (3 * math::pi as f32); + val inertia := circle * (0.5 * rr + half * half + 2 * half * off) + box * (4 * rr + length * length) / 12; + return mass_data{ mass = circle + box, center = (p1 + p2) * 0.5, inertia = inertia }; +} + +# A polygon's, as the triangles fanned from its first corner sum it. +def polygon_mass(s: &shape, density: f32): mass_data { + val origin := s.point(0); + var area: f32 = 0; + var center := vec2::zero; + var inertia: f32 = 0; + for i in 1..s.count - 1 { + val e1 := s.point(i) - origin; + val e2 := s.point(i + 1) - origin; + val d := e1.cross(e2); + val triangle := 0.5 * d; + area += triangle; + center = center + (e1 + e2) * (triangle / 3); + val xx := e1.x * e1.x + e2.x * e1.x + e2.x * e2.x; + val yy := e1.y * e1.y + e2.y * e1.y + e2.y * e2.y; + inertia += (0.25 / 3 * d) * (xx + yy); + } + return mass_data{} if area <= tiny; + center = center * (1 / area); + val mass := density * area; + # Of the corner it was summed about, moved to the center. + return mass_data{ mass = mass, center = origin + center, inertia = density * inertia - mass * center.length_squared }; +} diff --git a/physics2d/physics2d.sakura b/physics2d/physics2d.sakura new file mode 100644 index 0000000..445db37 --- /dev/null +++ b/physics2d/physics2d.sakura @@ -0,0 +1,74 @@ +#! Contains `physics2d`: what collides and moves in a plane, as a game of two +#! dimensions asks it. Shapes, circles, capsules, and convex polygons, each +#! about the origin of its body and placed by a `pose`; whether two meet, and +#! the `manifold` of where and how deep, which way to push them apart; where a +#! ray first meets one; an `aabb_tree` of many, which finds those near a box or +#! along a ray without passing over the rest; and a `grid` of solid cells, as a +#! tilemap's walls are, met as boxes, each but the faces it shares with a solid +#! neighbor, so a body slides along a floor of many cells as along one. +#! +#! And a `space` of bodies: each made of colliders, of shapes, a grid, or a +#! chain's segments, pulled by gravity, pushed by forces and by what it meets, +#! held to others by joints, and stepped forward in time as Box2D's soft step +#! solves it, on as many threads as it's given, swept through each step where +#! it moves fast enough to pass through what's thin, and sleeping where it and +#! all it rests on are still. A space answers which colliders a shape overlaps +#! and where a cast first meets one, and walks `character`s through it. +#! +#! The plane is `linear`'s x and y: x to the right, y up, and angles +#! counterclockwise, in radians. A polygon's corners are counterclockwise, and +#! each edge's normal faces out. A shape's surface is within it, so two shapes +#! touching meet, at a depth of 0. + +import std::math; +import malunal::linear; +module malunal::physics2d; + +# How near two numbers are taken as one, as lengths in a game's units are. +const tiny: f32 = 1e-6; + +# The point of a segment nearest a place. +def nearest_on_segment(p: vec2, a: vec2, b: vec2): vec2 { + val e := b - a; + val length_squared := e.dot(e); + return a if length_squared <= tiny * tiny; + val t := math::clamp((p - a).dot(e) / length_squared, 0f, 1f); + return a + e * t; +} + +# The points of two segments nearest one another: on `a1`-`a2` first, then on +# `b1`-`b2`, as Ericson's Real-Time Collision Detection finds them. +def nearest_of_segments(a1: vec2, a2: vec2, b1: vec2, b2: vec2): vec2[2] { + val d1 := a2 - a1; + val d2 := b2 - b1; + val r := a1 - b1; + val a := d1.dot(d1); + val e := d2.dot(d2); + val f := d2.dot(r); + var s: f32 = 0; + var t: f32 = 0; + if a <= tiny && e <= tiny { + return [a1, b1]; + } + if a <= tiny { + t = math::clamp(f / e, 0f, 1f); + } else { + val c := d1.dot(r); + if e <= tiny { + s = math::clamp(-c / a, 0f, 1f); + } else { + val b := d1.dot(d2); + val denominator := a * e - b * b; + s = denominator > tiny ? math::clamp((b * f - c * e) / denominator, 0f, 1f) : 0; + t = (b * s + f) / e; + if t < 0 { + t = 0; + s = math::clamp(-c / a, 0f, 1f); + } else if t > 1 { + t = 1; + s = math::clamp((b - c) / a, 0f, 1f); + } + } + } + return [a1 + d1 * s, b1 + d2 * t]; +} diff --git a/physics2d/pose.sakura b/physics2d/pose.sakura new file mode 100644 index 0000000..556373b --- /dev/null +++ b/physics2d/pose.sakura @@ -0,0 +1,91 @@ +#! Contains `rot`, a rotation in the plane, and `pose`, where a body is and +#! which way it's turned, which places its shapes. + +import std::math; +import std::serial; +import malunal::linear; +module malunal::physics2d; + +#! A rotation in the plane, counterclockwise, as its angle's cosine and sine, +#! so turning a vector takes no trigonometry. +@serial +pub struct rot { + @serial pub var c: f32 = 1; + @serial pub var s: f32; +} + +#! No rotation. +pub val rot::identity := rot{ 1, 0 }; + +#! A rotation by an angle, in radians, counterclockwise. +pub def rot::of(angle: f32): rot { + return rot{ math::cos(angle), math::sin(angle) }; +} + +#! Its angle, in radians, from -π to π. +pub val rot::angle: f32 { + get => math::atan2(this.s, this.c); +} + +pub def rot::equals(&this, other: &rot): bool { + return this.c == other.c && this.s == other.s; +} + +#! A vector turned by it. +pub def rot::apply(&this, v: vec2): vec2 { + return vec2{ this.c * v.x - this.s * v.y, this.s * v.x + this.c * v.y }; +} + +#! A vector turned back by it, as its inverse turns it. +pub def rot::unapply(&this, v: vec2): vec2 { + return vec2{ this.c * v.x + this.s * v.y, this.c * v.y - this.s * v.x }; +} + +#! It after another: turning by the product turns by `other`, then by this. +pub def rot::mul(&this, other: &rot): rot { + return rot{ this.c * other.c - this.s * other.s, this.s * other.c + this.c * other.s }; +} + +#! Where a body is in the plane, and which way it's turned: what a place of its +#! own, as its shapes' corners are, is in the plane. +@serial +pub struct pose { + @serial pub var at: vec2; + @serial pub var turn := rot::identity; +} + +#! At the origin, unturned. +pub val pose::identity := pose{}; + +#! A pose at a place, turned by an angle, in radians, counterclockwise. +pub def pose::of(at: vec2, angle: f32 = 0): pose { + return pose{ at = at, turn = rot::of(angle) }; +} + +pub def pose::equals(&this, other: &pose): bool { + return this.at == other.at && this.turn == other.turn; +} + +#! Where a place of the body's own is in the plane. +pub def pose::apply(&this, local: vec2): vec2 { + return this.at + this.turn.apply(local); +} + +#! Where a place of the plane is in the body's own. +pub def pose::unapply(&this, place: vec2): vec2 { + return this.turn.unapply(place - this.at); +} + +#! It after another: the pose of what's placed by `other` within what this +#! places. +pub def pose::mul(&this, other: &pose): pose { + return pose{ at = this.apply(other.at), turn = this.turn * other.turn }; +} + +#! Another pose of the plane, as one within what this places, of its own +#! places: what `this * found` is `other` of. +pub def pose::unapply_pose(&this, other: pose): pose { + val c := this.turn.c * other.turn.c + this.turn.s * other.turn.s; + val s := this.turn.c * other.turn.s - this.turn.s * other.turn.c; + return pose{ at = this.unapply(other.at), turn = rot{ c, s } }; +} diff --git a/physics2d/queries.sakura b/physics2d/queries.sakura new file mode 100644 index 0000000..71a0c3d --- /dev/null +++ b/physics2d/queries.sakura @@ -0,0 +1,115 @@ +#! Contains what a space is asked of the shapes in it: which colliders a shape +#! overlaps, and where a shape cast along a motion first meets one, as a +#! character's feet and a thrown stone ask. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics2d; + +#! Where a shape cast through a space first met one of its colliders: which, +#! of which body, how far along the motion, as a fraction of it, where on what +#! it met, and which way that faces, toward the shape cast. +pub struct space_cast { + pub var collider: collider_id; + pub var body: body_id; + pub var fraction: f32; + pub var point: vec2; + pub var normal: vec2; +} + +#! What a query of a space passes over: colliders on no layer of its `mask`; +#! sensors, unless `sensors`; and those whose data is `ignore`, where it isn't +#! 0, as the asker's own, a body and its colliders given an entity's bits. +pub struct query_filter { + pub var mask: u32 = 0xFFFFFFFF; + pub var sensors := false; + pub var ignore: u64 = 0; +} + +# Whether a query of a filter asks of a collider. +def space::passes(&this, c: u32, filter: &query_filter): bool { + val held := &this.colliders[c as u64].made; + return (held.layers & filter.mask) != 0 && (!held.sensor || filter.sensors) && (filter.ignore == 0 || held.data != filter.ignore); +} + +def space::named(&this, c: u32): collider_id { + return collider_id{ index = c, generation = this.colliders[c as u64].generation }; +} + +def space::body_named(&this, b: u32): body_id { + return body_id{ index = b, generation = this.bodies[b as u64].generation }; +} + +#! Visits each collider on a layer of a mask that a shape overlaps, where a +#! pose places it, sensors passed over, as `visit(collider, body)`, until it +#! gives false. +pub def space::overlap(&this, s: &shape, at: pose, mask: u32, visit: F): void where F: invokable { + this.overlap(s, at, query_filter{ mask = mask }, visit); +} + +#! Visits each collider a shape overlaps, where a pose places it, that a +#! filter asks of, as `visit(collider, body)`, until it gives false. +pub def space::overlap(&this, s: &shape, at: pose, filter: query_filter, visit: F): void where F: invokable { + this.tree.query(s.bounds(at), def(leaf: u32, data: u64): bool { + val c := data as u32; + return true if !this.passes(c, &filter); + val held := &this.colliders[data]; + val placed := this.bodies[held.body as u64].at; + var met := false; + if held.is_grid() { + met = this.grids[held.grid as u64].overlaps(placed, s, at); + } else { + met = overlaps(&held.made.shape, placed, s, at); + } + return true if !met; + return visit(this.named(c), this.body_named(held.body)); + }); +} + +#! Where a shape, cast along a motion of the plane from where a pose places +#! it, first meets a collider on a layer of a mask, sensors passed over, and +#! chains' segments and one-way colliders it begins behind: within a quarter of +#! the slop of what it meets, a little short of touching. A fraction of 0 where +#! it overlaps something as it begins. Colliders of `except`, a body of its +#! own, as a character's, are passed over. +pub def space::shape_cast(&this, s: &shape, at: pose, motion: vec2, mask: u32 = 0xFFFFFFFF, except: body_id = body_id{}): maybe { + return this.shape_cast(s, at, motion, query_filter{ mask = mask }, except); +} + +#! Where a shape, cast along a motion as `shape_cast` casts it, first meets a +#! collider a filter asks of. +pub def space::shape_cast(&this, s: &shape, at: pose, motion: vec2, filter: query_filter, except: body_id = body_id{}): maybe { + var best: maybe = nothing{}; + var first: f32 = 2; + val tolerance := 0.25 * this.slop; + val moved := pose{ at = at.at + motion, turn = at.turn }; + val box := s.bounds(at).merged(s.bounds(moved)); + this.tree.query(box, def(leaf: u32, data: u64): bool { + val c := data as u32; + return true if !this.passes(c, &filter) || this.behind_one_way(c, s, at) || this.colliders[data].body == except.index; + val held := &this.colliders[data]; + val placed := this.bodies[held.body as u64].at; + if held.is_grid() { + val cells := &this.grids[held.grid as u64]; + cells.cells_in(local_box(box, placed), def(x: u32, y: u32): bool { + val cell := cells.box_of(x, y); + val solid := shape::box(cell.half_size, cell.center); + val hit := shape_cast(&solid, placed, s, at, motion, tolerance) else { return true; }; + if hit.fraction < first { + first = hit.fraction; + best = space_cast{ collider = this.named(c), body = this.body_named(held.body), fraction = hit.fraction, point = hit.point, normal = hit.normal }; + } + return true; + }); + return true; + } + val hit := shape_cast(&held.made.shape, placed, s, at, motion, tolerance) else { return true; }; + if hit.fraction < first { + first = hit.fraction; + best = space_cast{ collider = this.named(c), body = this.body_named(held.body), fraction = hit.fraction, point = hit.point, normal = hit.normal }; + } + return true; + }); + return best; +} diff --git a/physics2d/shape.sakura b/physics2d/shape.sakura new file mode 100644 index 0000000..c9e901e --- /dev/null +++ b/physics2d/shape.sakura @@ -0,0 +1,339 @@ +#! Contains `shape`: a circle, a capsule, or a convex polygon, about the origin +#! of its body; the box holding it where a pose places it; whether it holds a +#! place; and where a ray first meets it. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics2d; + +#! The most corners a polygon has. +pub const max_corners: u32 = 8; + +#! What a shape is. +pub enum shape_kind: u8 { + #! The places within its radius of its middle. + circle, + #! The places within its radius of a segment, between its two ends, as a + #! pill; of a radius of 0, the segment itself, as a thin wall, or a segment + #! of a chain. + capsule, + #! A convex polygon of three to eight corners. + polygon, +} + +#! A shape of a body, about the body's origin, as a pose places it: a circle, +#! a capsule, or a convex polygon, each its points and a radius around them. A +#! circle is its middle, a capsule its two ends, and a polygon its corners, +#! counterclockwise, each edge's normal facing out. +pub struct shape { + var _kind: shape_kind; + var _radius: f32; + var _count: u32; + var _points: vec2[8]; + var _normals: vec2[8]; # Of edge `i`, from point `i` to the next. + var _chained: u8; # Of a chain's segment: 1, and 2 where it has a segment before it, 4 where after, at points 2 and 3. +} + +#! Where a ray met a shape: how far along it, where, and which way the shape +#! faces there. +pub struct ray_hit { + pub var distance: f32; + pub var point: vec2; + pub var normal: vec2; +} + +#! A circle of a radius, about a middle, the body's origin at first. +pub def shape::circle(radius: f32, center: vec2 = vec2::zero): shape { + var made := shape{ _kind = shape_kind::circle, _radius = radius, _count = 1 }; + made._points[0] = center; + return made; +} + +#! A capsule of a radius about the segment between two places: a circle of +#! the radius, where they're one place. +pub def shape::capsule(a: vec2, b: vec2, radius: f32): shape { + return shape::circle(radius, a) if (b - a).length_squared <= tiny * tiny; + var made := shape{ _kind = shape_kind::capsule, _radius = radius, _count = 2 }; + made._points[0] = a; + made._points[1] = b; + made.find_normals(); + return made; +} + +#! A capsule standing up, as a character's body: so wide and so high in all, +#! its ends round, about a middle. Narrower than it's high, or a circle. +pub def shape::pill(width: f32, height: f32, center: vec2 = vec2::zero): shape { + val radius := width / 2; + val reach := math::max(height / 2 - radius, 0f); + return shape::capsule(center - vec2{ 0, reach }, center + vec2{ 0, reach }, radius); +} + +#! A segment between two places, of no thickness, as a capsule of no radius. +pub def shape::segment(a: vec2, b: vec2): shape { + return shape::capsule(a, b, 0); +} + +#! A segment of a chain, from `a` to `b`, between the places of the segments +#! before and after it, as `space::attach_chain` makes them: met only on the +#! side its normal faces, to the right going from `a` to `b`, as a polygon's +#! counterclockwise edges face out, and passed over at its ends where they join +#! the chain's segments beside them flat or hollow, so a body slides along a +#! chain as along one surface. Where `before` or `after` is nothing, its end +#! is the chain's own, met as a segment's is. +pub def shape::chain_segment(a: vec2, b: vec2, before: maybe = nothing{}, after: maybe = nothing{}): shape { + var made := shape::capsule(a, b, 0); + return made if made._count != 2; + made._chained = 1; + if before is some(p) { + made._points[2] = p; + made._chained = made._chained | 2; + } + if after is some(p) { + made._points[3] = p; + made._chained = made._chained | 4; + } + return made; +} + +#! Whether it's a segment of a chain, met only on the side its normal faces. +pub val shape::is_one_sided: bool { + get => this._chained != 0; +} + +#! A box reaching so far each way from its middle, turned by an angle, in +#! radians. +pub def shape::box(half: vec2, center: vec2 = vec2::zero, angle: f32 = 0): shape { + val turn := rot::of(angle); + var made := shape{ _kind = shape_kind::polygon, _count = 4 }; + val corners: vec2[4] = [vec2{ -half.x, -half.y }, vec2{ half.x, -half.y }, vec2{ half.x, half.y }, vec2{ -half.x, half.y }]; + for i in 0..4u { + made._points[i] = center + turn.apply(corners[i]); + } + made.find_normals(); + return made; +} + +#! The convex polygon around places, three to eight of its corners among +#! them: what's inside it and on its edges left out. Nothing where the places +#! hold no area, or their hull has more than eight corners. +pub def shape::polygon(places: span): maybe { + var sorted := vector::::new(); + for i in 0..places.length { + sorted.append(places[i]); + } + sorted.sort_by(before_in_x); + # Andrew's monotone chain: the hull's lower half, left to right, then its + # upper, right to left, each corner turning left of the last two. + var hull := vector::::new(); + for i in 0..sorted.length { + while hull.length >= 2 && turning(hull[hull.length - 2], hull[hull.length - 1], sorted[i]) <= tiny { + hull.truncate(); + } + hull.append(sorted[i]); + } + val lower := hull.length + 1; + var i := sorted.length; + while i > 1 { + i--; + val p := sorted[i - 1]; + while hull.length >= lower && turning(hull[hull.length - 2], hull[hull.length - 1], p) <= tiny { + hull.truncate(); + } + hull.append(p); + } + # Its last corner is its first again. + if hull.length > 0 { + hull.truncate(); + } + return nothing{} if hull.length < 3 || hull.length > max_corners as u64; + var made := shape{ _kind = shape_kind::polygon, _count = hull.length as u32 }; + for k in 0..hull.length { + made._points[k] = hull[k]; + } + made.find_normals(); + return made; +} + +# Whether a place comes before another, left to right, then bottom to top. +def before_in_x(a: &vec2, b: &vec2): bool { + return a.x < b.x if a.x != b.x; + return a.y < b.y; +} + +# Twice the area of the triangle of three places, positive where they turn +# counterclockwise. +def turning(a: vec2, b: vec2, c: vec2): f32 { + return (b - a).cross(c - a); +} + +# Finds the normal of each edge: its direction turned a quarter clockwise, +# which faces out of corners counterclockwise. +def shape::find_normals(&mut this): void { + for i in 0..this._count { + val edge := this._points[(i + 1) % this._count] - this._points[i]; + this._normals[i] = vec2{ edge.y, -edge.x }.normalized(); + } +} + +pub val shape::kind: shape_kind { + get => this._kind; +} + +#! How far around its points it reaches: a circle's or a capsule's radius, +#! and none of a polygon. +pub val shape::radius: f32 { + get => this._radius; +} + +#! How many points it's of: a circle 1, a capsule 2, and a polygon its +#! corners. +pub val shape::count: u32 { + get => this._count; +} + +#! A point of it: a circle's middle, a capsule's end, or a polygon's corner. +pub def shape::point(&this, i: u32): vec2 { + return this._points[i]; +} + +#! The normal of an edge of a capsule or a polygon, from point `i` to the +#! next, facing out. +pub def shape::normal(&this, i: u32): vec2 { + return this._normals[i]; +} + +#! The box holding it, where a pose places it. +pub def shape::bounds(&this, at: pose): aabb { + var low := at.apply(this._points[0]); + var high := low; + for i in 1..this._count { + val p := at.apply(this._points[i]); + low = low.min(p); + high = high.max(p); + } + val r := vec2{ this._radius, this._radius }; + return aabb{ low - r, high + r }; +} + +#! Whether it holds a place of the plane, where a pose places it, its surface +#! among it. +pub def shape::contains(&this, at: pose, p: vec2): bool { + val local := at.unapply(p); + if this._kind == shape_kind::circle { + return (local - this._points[0]).length_squared <= this._radius * this._radius; + } + if this._kind == shape_kind::capsule { + val nearest := nearest_on_segment(local, this._points[0], this._points[1]); + return (local - nearest).length_squared <= this._radius * this._radius; + } + for i in 0..this._count { + return false if this._normals[i].dot(local - this._points[i]) > 0; + } + return true; +} + +#! Where a ray first meets it, where a pose places it: from a place, along a +#! direction of length 1, as far as `reach`. A ray beginning within it meets +#! it at 0, facing back along the ray. +pub def shape::ray_cast(&this, at: pose, origin: vec2, direction: vec2, reach: f32): maybe { + val o := at.unapply(origin); + val d := at.turn.unapply(direction); + var found: maybe = nothing{}; + match this._kind { + circle => found = ray_circle(o, d, reach, this._points[0], this._radius); + capsule => found = ray_capsule(o, d, reach, this._points[0], this._points[1], this._radius); + polygon => found = this.ray_polygon(o, d, reach); + } + if found is some(hit) { + return ray_hit{ distance = hit.distance, point = at.apply(hit.point), normal = at.turn.apply(hit.normal) }; + } + return nothing{}; +} + +# A ray, of the shape's own places, meeting a circle. +def ray_circle(o: vec2, d: vec2, reach: f32, center: vec2, radius: f32): maybe { + val s := o - center; + val c := s.dot(s) - radius * radius; + return ray_hit{ distance = 0, point = o, normal = d * -1f } if c <= 0; + val b := s.dot(d); + return nothing{} if b > 0; + val disc := b * b - c; + return nothing{} if disc < 0; + val t := -b - math::sqrt(disc); + return nothing{} if t > reach; + val p := o + d * t; + return ray_hit{ distance = t, point = p, normal = (p - center) * (1 / radius) }; +} + +# A ray meeting a capsule: its flat sides, where it meets them between its +# ends, else its round ends; or a segment, of no radius, from either side. +def ray_capsule(o: vec2, d: vec2, reach: f32, a: vec2, b: vec2, radius: f32): maybe { + val nearest := nearest_on_segment(o, a, b); + if (o - nearest).length_squared <= radius * radius { + return ray_hit{ distance = 0, point = o, normal = d * -1f }; + } + val along := (b - a).normalized(); + val length := (b - a).length; + # The side facing the ray's beginning. + var side := along.perpendicular(); + if side.dot(o - a) < 0 { + side = side * -1f; + } + val toward := d.dot(side); + var best: maybe = nothing{}; + if toward < 0 { + val t := (side.dot(o - a) - radius) / -toward; + if t >= 0 && t <= reach { + val p := o + d * t; + val s := (p - a).dot(along); + if s >= 0 && s <= length { + return ray_hit{ distance = t, point = p, normal = side }; + } + } + } + return nothing{} if radius <= 0; + val first := ray_circle(o, d, reach, a, radius); + val second := ray_circle(o, d, reach, b, radius); + if first is some(hit) { + best = hit; + } + if second is some(hit) { + if best is some(held) { + if hit.distance < held.distance { + best = hit; + } + } else { + best = hit; + } + } + return best; +} + +# A ray meeting a polygon, clipped by each edge's side in turn, as Cyrus and +# Beck clip a line: where it enters the last side it crosses into is where it +# meets the polygon. +def shape::ray_polygon(&this, o: vec2, d: vec2, reach: f32): maybe { + var lower: f32 = 0; + var upper := reach; + var entered: i64 = -1; + for i in 0..this._count { + val n := this._normals[i]; + val numerator := n.dot(this._points[i] - o); + val denominator := n.dot(d); + if denominator == 0 { + return nothing{} if numerator < 0; + continue; + } + val t := numerator / denominator; + if denominator < 0 && t > lower { + lower = t; + entered = i as i64; + } else if denominator > 0 && t < upper { + upper = t; + } + return nothing{} if upper < lower; + } + return ray_hit{ distance = 0, point = o, normal = d * -1f } if entered < 0; + return ray_hit{ distance = lower, point = o + d * lower, normal = this._normals[entered as u32] }; +} diff --git a/physics2d/sleep.sakura b/physics2d/sleep.sakura new file mode 100644 index 0000000..83ffbf9 --- /dev/null +++ b/physics2d/sleep.sakura @@ -0,0 +1,119 @@ +#! Contains how a space's bodies sleep: those that touch, or a joint holds +#! together, are an island, found anew each step, and an island sleeps when +#! all its bodies have been still for half a second, so a settled pile costs +#! nothing until something wakes it. A kinematic body sleeps alone, when it +#! has been still as long. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics2d; + +# How long, in seconds, a body is still before it may sleep. +const time_to_sleep: f32 = 0.5; + +# The first body of the island a body is of, each body passed on the way +# pointed nearer it, so the next finding is shorter. +def root_of(parent: &mut vector, b: u32): u32 { + var x := b; + while parent[x as u64] != x { + val up := parent[parent[x as u64] as u64]; + parent[x as u64] = up; + x = up; + } + return x; +} + +def join(parent: &mut vector, a: u32, b: u32): void { + val ra := root_of(parent, a); + val rb := root_of(parent, b); + if ra != rb { + parent[math::max(ra, rb) as u64] = math::min(ra, rb); + } +} + +# Finds the islands of awake dynamic bodies, and puts to sleep those all of +# whose bodies have been still long enough. +def space::sleep_islands(&mut this, dt: f32): void { + var parent := move(this.islands); + parent.clear(); + parent.resize(this.bodies.length, none); + for b in 0..this.bodies.length { + val body := &this.bodies[b]; + if body.alive && body.awake && body.kind == body_kind::dynamic { + parent[b] = b as u32; + } + } + for k in 0..this.contacts.length { + val c := &this.contacts[k]; + continue if !c.alive || !c.touching; + val a := c.body_a; + val b := c.body_b; + if parent[a as u64] != none && parent[b as u64] != none { + join(&mut parent, a, b); + } else if parent[a as u64] != none && this.bodies[b as u64].kind == body_kind::kinematic { + this.keep_awake_on(a, b); + } else if parent[b as u64] != none && this.bodies[a as u64].kind == body_kind::kinematic { + this.keep_awake_on(b, a); + } + } + this.join_jointed(&mut parent); + # Each island's least time still, kept at its root. + for b in 0..this.bodies.length { + continue if parent[b] == none; + val root := root_of(&mut parent, b as u32) as u64; + this.bodies[root].sleep_time = math::min(this.bodies[root].sleep_time, this.bodies[b].sleep_time); + } + for b in 0..this.bodies.length { + continue if parent[b] == none; + val root := root_of(&mut parent, b as u32); + continue if this.bodies[root as u64].sleep_time < time_to_sleep; + # Linked after its root, which heads the group. + this.bodies[b].awake = false; + this.bodies[b].velocity = vec2::zero; + this.bodies[b].spin = 0; + this.bodies[b].group = root; + if b as u32 != root { + this.bodies[b].next_in_group = this.bodies[root as u64].next_in_group; + this.bodies[root as u64].next_in_group = b as u32; + } + } + # A kinematic body still long enough sleeps alone. + for b in 0..this.bodies.length { + val body := &this.bodies[b]; + if body.alive && body.awake && body.kind == body_kind::kinematic && body.sleep_time >= time_to_sleep { + this.bodies[b].awake = false; + this.bodies[b].group = b as u32; + } + } + this.islands = move(parent); +} + +# Keeps a dynamic body awake where it rests on a kinematic body that moves. +def space::keep_awake_on(&mut this, b: u32, kinematic: u32): void { + val k := &this.bodies[kinematic as u64]; + if k.velocity.length_squared > 0 || k.spin != 0 { + this.bodies[b as u64].sleep_time = 0; + } +} + +# Wakes a body, and every body of the group it sleeps with, and marks it as +# having been still for no time. +def space::wake_body(&mut this, b: u32): void { + return if this.bodies[b as u64].kind == body_kind::static; + this.bodies[b as u64].sleep_time = 0; + return if this.bodies[b as u64].awake; + var m := this.bodies[b as u64].group; + if m == none { + this.bodies[b as u64].awake = true; + return; + } + while m != none { + val next := this.bodies[m as u64].next_in_group; + this.bodies[m as u64].awake = true; + this.bodies[m as u64].sleep_time = 0; + this.bodies[m as u64].group = none; + this.bodies[m as u64].next_in_group = none; + m = next; + } +} diff --git a/physics2d/solver.sakura b/physics2d/solver.sakura new file mode 100644 index 0000000..fba1792 --- /dev/null +++ b/physics2d/solver.sakura @@ -0,0 +1,517 @@ +#! Contains how a space solves a step, as Box2D's soft step solves one: in +#! substeps, each of which moves velocities by forces, pushes apart what meets, +#! softly, moves the bodies, and pushes again without undoing overlaps; then +#! bounces what met fast enough, and keeps each contact's impulses for the +#! next step to begin with. +#! +#! A contact pushes as a stiff, damped spring of the space's frequency, so an +#! overlap is undone over a few substeps, no faster than the push speed, and a +#! stack doesn't jitter. Points apart within the speculative margin push only +#! as much as would close the gap in a substep, so what falls stops at what's +#! below it rather than in it. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics2d; + +# How soft a constraint is, as a damped spring of a frequency is: how much of +# its error it undoes each second, and how much of its impulse it gives. +struct softness { + var bias_rate: f32; + var mass_scale: f32 = 1; + var impulse_scale: f32; +} + +def soft_of(hertz: f32, damping: f32, h: f32): softness { + return softness{} if hertz == 0; + val omega := 2 * math::pi as f32 * hertz; + val a1 := 2 * damping + h * omega; + val a2 := h * omega * a1; + val a3 := 1 / (1 + a2); + return softness{ bias_rate = omega / a1, mass_scale = a2 * a3, impulse_scale = a3 }; +} + +# A body as a step moves it: its velocities, and how far its center has moved +# and it has turned since the step began. It's eight numbers, which +# `wide_contact`'s lanes gather by where each begins. +struct body_state { + var v: vec2; + var w: f32; + var pad: f32; + var dp: vec2; + var dq: rot; +} + +# How a body's velocities change each substep: by its forces and gravity, and +# what its damping keeps of them. +struct body_motion { + var dv: vec2; + var dw: f32; + var linear_keep: f32 = 1; + var angular_keep: f32 = 1; +} + +# A point of a contact as the solver pushes at it: where it is from each +# body's center, how far apart the two are there but for how far they've +# moved, and the impulses pushing them apart and along. +struct point_constraint { + var anchor_a: vec2; + var anchor_b: vec2; + var base_separation: f32; + var normal_impulse: f32; + var tangent_impulse: f32; + var max_impulse: f32; + var impact: f32; # What stopped it meeting fast, as the step began. + var normal_mass: f32; + var tangent_mass: f32; + var relative_velocity: f32; +} + +struct contact_constraint { + var a: u32; # States. + var b: u32; + var contact: u32; + var normal: vec2; + var friction: f32; + var restitution: f32; + var ma: f32; + var ia: f32; + var mb: f32; + var ib: f32; + var soft: softness; + var count: u32; + var points: point_constraint[2]; +} + +# What a step works in, kept from one to the next so it isn't made anew: the +# first state is of what doesn't move. +struct solver_scratch { + var states: vector; + var motions: vector; + var bodies: vector; + var constraints: vector; + var joints: vector; # Joints of a moving body. + var joint_soft: softness; + var wide: vector; + var overflow: vector; # Constraints of no color. + var colored: vector; # Each color's bodies, a bit each. + var color_of: vector; + var color_groups: u32[25]; # Where each color's lanes begin. +} + +# The most a body turns in a substep, a quarter of a half turn, so a fast spin +# doesn't skip through what it meets. +const most_turn: f32 = 0.25 * 3.14159265; + +# A rotation turned further by an angle, kept of length 1. +def turned(q: rot, angle: f32): rot { + val c := q.c - angle * q.s; + val s := q.s + angle * q.c; + val length := math::sqrt(c * c + s * s); + return length > 0 ? rot{ c / length, s / length } : rot::identity; +} + +# The velocity of a place a body turning at `w` is `r` from its center of. +def spun(w: f32, r: vec2): vec2 { + return vec2{ -w * r.y, w * r.x }; +} + +def space::solve(&mut this, dt: f32): void { + val n: u32 = this.substeps > 0 ? this.substeps : 1; + val h := dt / n as f32; + val inv_h := 1 / h; + var s := move(this.solver); + this.gather(&mut s, h); + this.prepare_contacts(&mut s, h); + this.prepare_joints(&mut s, h); + stop_impacts(&mut s, dt, 2 * this.push_speed); + color_contacts(&mut s); + val max_spin := most_turn * inv_h; + this.crew.start(this.threads); + for i in 0..n { + integrate_velocities(&mut s, this.max_speed, max_spin); + this.warm_joints(&mut s); + this.wide_stage(&mut s, true, inv_h, this.push_speed, true); + warm_contacts(&mut s); + this.solve_joints(&mut s, h, true); + this.wide_stage(&mut s, false, inv_h, this.push_speed, true); + solve_contacts(&mut s, inv_h, this.push_speed, true); + integrate_positions(&mut s, h); + this.solve_joints(&mut s, h, false); + this.wide_stage(&mut s, false, inv_h, this.push_speed, false); + solve_contacts(&mut s, inv_h, this.push_speed, false); + } + unpack_contacts(&mut s); + bounce(&mut s, this.restitution_threshold); + this.keep_impulses(&s); + this.finish(&s, dt); + this.solver = move(s); +} + +# Gives each moving body a state, and how its forces move it each substep. +def space::gather(&mut this, s: &mut solver_scratch, h: f32): void { + s.states.clear(); + s.motions.clear(); + s.bodies.clear(); + s.states.append(body_state{}); + s.motions.append(body_motion{}); + s.bodies.append(none); + for b in 0..this.bodies.length { + if !this.bodies[b].alive || !this.moves(b as u32) { + this.bodies[b].slot = 0; + continue; + } + this.bodies[b].slot = s.states.length as u32; + val body := &this.bodies[b]; + s.states.append(body_state{ v = body.velocity, w = body.spin }); + if body.kind == body_kind::dynamic { + s.motions.append(body_motion{ + dv = ((this.gravity + body.gravity) * body.gravity_scale + body.force * body.inv_mass) * h, + dw = h * body.inv_inertia * body.torque, + linear_keep = 1 / (1 + h * body.linear_damping), + angular_keep = 1 / (1 + h * body.angular_damping), + }); + } else { + s.motions.append(body_motion{}); + } + s.bodies.append(b as u32); + } +} + +def space::prepare_contacts(&this, s: &mut solver_scratch, h: f32): void { + s.constraints.clear(); + val hertz := math::min(this.contact_hertz, 0.25 / h); + val soft := soft_of(hertz, this.contact_damping, h); + # Against what doesn't move, twice as stiff. + val stiff := soft_of(2 * hertz, this.contact_damping, h); + for k in 0..this.contacts.length { + val c := &this.contacts[k]; + continue if !c.alive || !c.touching || c.passing; + val a := &this.bodies[c.body_a as u64]; + val b := &this.bodies[c.body_b as u64]; + continue if a.slot == 0 && b.slot == 0; + val n := c.manifold.normal; + val t := vec2{ n.y, -n.x }; + var made := contact_constraint{ + a = a.slot, b = b.slot, contact = k as u32, normal = n, friction = c.friction, restitution = c.restitution, + ma = a.inv_mass, ia = a.inv_inertia, mb = b.inv_mass, ib = b.inv_inertia, + soft = a.inv_mass == 0 || b.inv_mass == 0 ? stiff : soft, count = c.manifold.count, + }; + for j in 0..c.manifold.count { + val mp := &c.manifold.points[j]; + val ra := mp.point - a.center; + val rb := mp.point - b.center; + val rna := ra.cross(n); + val rnb := rb.cross(n); + val kn := made.ma + made.mb + made.ia * rna * rna + made.ib * rnb * rnb; + val rta := ra.cross(t); + val rtb := rb.cross(t); + val kt := made.ma + made.mb + made.ia * rta * rta + made.ib * rtb * rtb; + val vra := a.velocity + spun(a.spin, ra); + val vrb := b.velocity + spun(b.spin, rb); + made.points[j] = point_constraint{ + anchor_a = ra, anchor_b = rb, + base_separation = -mp.depth - (rb - ra).dot(n), + normal_impulse = c.normal_impulse[j], tangent_impulse = c.tangent_impulse[j], + normal_mass = kn > 0 ? 1 / kn : 0f, tangent_mass = kt > 0 ? 1 / kt : 0f, + relative_velocity = n.dot(vrb - vra), + }; + } + s.constraints.append(made); + } +} + +# Stops what meets faster than a threshold before the substeps begin, as far +# as closes its gap through the step, over a few passes, so a crate dropped +# flat lands flat: solved within the substeps, the impulse that stops it would +# be given again as each begins, and taken back, unevenly between its points, +# throwing it. What stops it is kept apart from the impulses the substeps +# begin with, but for bouncing. +def stop_impacts(s: &mut solver_scratch, dt: f32, threshold: f32): void { + for pass in 0..4u { + for i in 0..s.constraints.length { + val c := &mut s.constraints[i]; + var fast := false; + for j in 0..c.count { + if c.points[j].relative_velocity < -threshold { + fast = true; + } + } + continue if !fast; + var va := s.states[c.a as u64].v; + var wa := s.states[c.a as u64].w; + var vb := s.states[c.b as u64].v; + var wb := s.states[c.b as u64].w; + val n := c.normal; + for j in 0..c.count { + val cp := &mut c.points[j]; + val ra := cp.anchor_a; + val rb := cp.anchor_b; + val gap := cp.base_separation + (rb - ra).dot(n); + val least := gap > 0 ? -gap / dt : 0f; + val vn := (vb + spun(wb, rb) - va - spun(wa, ra)).dot(n); + val sum := math::max(cp.impact - cp.normal_mass * (vn - least), 0f); + val impulse := sum - cp.impact; + cp.impact = sum; + cp.max_impulse = math::max(cp.max_impulse, sum); + val p := n * impulse; + va = va - p * c.ma; + wa -= c.ia * ra.cross(p); + vb = vb + p * c.mb; + wb += c.ib * rb.cross(p); + } + s.states[c.a as u64].v = va; + s.states[c.a as u64].w = wa; + s.states[c.b as u64].v = vb; + s.states[c.b as u64].w = wb; + } + } +} + +def integrate_velocities(s: &mut solver_scratch, max_speed: f32, max_spin: f32): void { + for i in 1..s.states.length { + val m := &s.motions[i]; + val st := &mut s.states[i]; + var v := st.v * m.linear_keep + m.dv; + var w := st.w * m.angular_keep + m.dw; + val speed_squared := v.length_squared; + if speed_squared > max_speed * max_speed { + v = v * (max_speed / math::sqrt(speed_squared)); + } + if w * w > max_spin * max_spin { + w = w * (max_spin / math::abs(w)); + } + st.v = v; + st.w = w; + } +} + +def integrate_positions(s: &mut solver_scratch, h: f32): void { + for i in 1..s.states.length { + val st := &mut s.states[i]; + st.dq = turned(st.dq, h * st.w); + st.dp = st.dp + st.v * h; + } +} + +# Of the contacts of no color, one at a time. +def warm_contacts(s: &mut solver_scratch): void { + for o in 0..s.overflow.length { + val c := &s.constraints[s.overflow[o] as u64]; + var va := s.states[c.a as u64].v; + var wa := s.states[c.a as u64].w; + var vb := s.states[c.b as u64].v; + var wb := s.states[c.b as u64].w; + val n := c.normal; + val t := vec2{ n.y, -n.x }; + for j in 0..c.count { + val cp := &c.points[j]; + val p := n * cp.normal_impulse + t * cp.tangent_impulse; + wa -= c.ia * cp.anchor_a.cross(p); + va = va - p * c.ma; + wb += c.ib * cp.anchor_b.cross(p); + vb = vb + p * c.mb; + } + s.states[c.a as u64].v = va; + s.states[c.a as u64].w = wa; + s.states[c.b as u64].v = vb; + s.states[c.b as u64].w = wb; + } +} + +# Worked a number at a time rather than as `vec2`s: sakurac keeps numbers in +# registers, where it passes small vectors through memory, which made this, +# the hottest loop of a step, several times slower. +def solve_contacts(s: &mut solver_scratch, inv_h: f32, push: f32, use_bias: bool): void { + val states := s.states.slice; + val constraints := s.constraints.slice; + for o in 0..s.overflow.length { + val c := &mut constraints[s.overflow[o] as u64]; + val a := c.a as u64; + val b := c.b as u64; + var vax := states[a].v.x; + var vay := states[a].v.y; + var wa := states[a].w; + var vbx := states[b].v.x; + var vby := states[b].v.y; + var wb := states[b].w; + val dpx := states[b].dp.x - states[a].dp.x; + val dpy := states[b].dp.y - states[a].dp.y; + val qac := states[a].dq.c; + val qas := states[a].dq.s; + val qbc := states[b].dq.c; + val qbs := states[b].dq.s; + val nx := c.normal.x; + val ny := c.normal.y; + val ma := c.ma; + val ia := c.ia; + val mb := c.mb; + val ib := c.ib; + for j in 0..c.count { + val cp := &mut c.points[j]; + val rax := cp.anchor_a.x; + val ray := cp.anchor_a.y; + val rbx := cp.anchor_b.x; + val rby := cp.anchor_b.y; + # How far apart they are now: as they began, and as far as each anchor + # has moved and turned since. + val dx := dpx + (qbc * rbx - qbs * rby) - (qac * rax - qas * ray); + val dy := dpy + (qbs * rbx + qbc * rby) - (qas * rax + qac * ray); + val separation := dx * nx + dy * ny + cp.base_separation; + var bias: f32 = 0; + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if separation > 0 { + # Apart: only what closes the gap this substep. + bias = separation * inv_h; + } else if use_bias { + bias = c.soft.bias_rate * separation; + if bias < -push { + bias = -push; + } + mass_scale = c.soft.mass_scale; + impulse_scale = c.soft.impulse_scale; + } + val vn := (vbx - wb * rby - vax + wa * ray) * nx + (vby + wb * rbx - vay - wa * rax) * ny; + val before := cp.normal_impulse; + var sum := before - cp.normal_mass * mass_scale * (vn + bias) - impulse_scale * before; + if sum < 0 { + sum = 0; + } + val impulse := sum - before; + cp.normal_impulse = sum; + if impulse > cp.max_impulse { + cp.max_impulse = impulse; + } + val px := nx * impulse; + val py := ny * impulse; + vax -= px * ma; + vay -= py * ma; + wa -= ia * (rax * py - ray * px); + vbx += px * mb; + vby += py * mb; + wb += ib * (rbx * py - rby * px); + } + # Friction, of no more than its share of what pushes them apart, along + # the tangent: the normal turned a quarter clockwise. + val tx := ny; + val ty := -nx; + for j in 0..c.count { + val cp := &mut c.points[j]; + val rax := cp.anchor_a.x; + val ray := cp.anchor_a.y; + val rbx := cp.anchor_b.x; + val rby := cp.anchor_b.y; + val vt := (vbx - wb * rby - vax + wa * ray) * tx + (vby + wb * rbx - vay - wa * rax) * ty; + val most := c.friction * cp.normal_impulse; + val before := cp.tangent_impulse; + var sum := before - cp.tangent_mass * vt; + if sum > most { + sum = most; + } else if sum < -most { + sum = -most; + } + val impulse := sum - before; + cp.tangent_impulse = sum; + val px := tx * impulse; + val py := ty * impulse; + vax -= px * ma; + vay -= py * ma; + wa -= ia * (rax * py - ray * px); + vbx += px * mb; + vby += py * mb; + wb += ib * (rbx * py - rby * px); + } + states[a].v.x = vax; + states[a].v.y = vay; + states[a].w = wa; + states[b].v.x = vbx; + states[b].v.y = vby; + states[b].w = wb; + } +} + +# Bounces what met faster than the threshold, as much as its restitution +# keeps of how fast it met: only at points that pushed, so a speculative +# point that never closed doesn't bounce. +def bounce(s: &mut solver_scratch, threshold: f32): void { + for i in 0..s.constraints.length { + val c := &mut s.constraints[i]; + continue if c.restitution == 0; + var va := s.states[c.a as u64].v; + var wa := s.states[c.a as u64].w; + var vb := s.states[c.b as u64].v; + var wb := s.states[c.b as u64].w; + val n := c.normal; + for j in 0..c.count { + val cp := &mut c.points[j]; + continue if cp.relative_velocity > -threshold || cp.max_impulse == 0; + val ra := cp.anchor_a; + val rb := cp.anchor_b; + val vn := (vb + spun(wb, rb) - va - spun(wa, ra)).dot(n); + var impulse := -cp.normal_mass * (vn + c.restitution * cp.relative_velocity); + val sum := math::max(cp.normal_impulse + impulse, 0f); + impulse = sum - cp.normal_impulse; + cp.normal_impulse = sum; + cp.max_impulse = math::max(cp.max_impulse, impulse); + val p := n * impulse; + va = va - p * c.ma; + wa -= c.ia * ra.cross(p); + vb = vb + p * c.mb; + wb += c.ib * rb.cross(p); + } + s.states[c.a as u64].v = va; + s.states[c.a as u64].w = wa; + s.states[c.b as u64].v = vb; + s.states[c.b as u64].w = wb; + } +} + +def space::keep_impulses(&mut this, s: &solver_scratch): void { + for i in 0..s.constraints.length { + val c := &s.constraints[i]; + for j in 0..c.count { + this.contacts[c.contact as u64].normal_impulse[j] = c.points[j].normal_impulse; + this.contacts[c.contact as u64].tangent_impulse[j] = c.points[j].tangent_impulse; + } + } +} + +# Puts each moving body where its state moved it, its colliders' leaves with +# it, and times how long it's been still. +def space::finish(&mut this, s: &solver_scratch, dt: f32): void { + val still := 0.05 * this.unit; + for i in 1..s.states.length { + val b := s.bodies[i] as u64; + val st := &s.states[i]; + val began := this.bodies[b].center; + val turned_from := this.bodies[b].at.turn; + val center := began + st.dp; + val turn := normalized(st.dq * turned_from); + this.bodies[b].center = center; + this.bodies[b].at = pose{ at = center - turn.apply(this.bodies[b].local_center), turn = turn }; + this.bodies[b].velocity = st.v; + this.bodies[b].spin = st.w; + this.bodies[b].force = vec2::zero; + this.bodies[b].torque = 0; + val speed := st.v.length + math::abs(st.w) * this.bodies[b].extent; + if !this.bodies[b].can_sleep || speed > still { + this.bodies[b].sleep_time = 0; + } else { + this.bodies[b].sleep_time += dt; + } + val count := this.fast.length; + this.note_fast(b as u32, sweep{ local_center = this.bodies[b].local_center, c1 = began, c2 = center, q1 = turned_from, q2 = turn }); + if this.fast.length == count { + this.place_colliders(b as u32); + } + } + this.sweep_fast(); +} + +# A rotation kept of length 1. +def normalized(q: rot): rot { + val length := math::sqrt(q.c * q.c + q.s * q.s); + return length > 0 ? rot{ q.c / length, q.s / length } : rot::identity; +} diff --git a/physics2d/space.sakura b/physics2d/space.sakura new file mode 100644 index 0000000..4b7ef8b --- /dev/null +++ b/physics2d/space.sakura @@ -0,0 +1,563 @@ +#! Contains `space`, where bodies move: each made of colliders, pulled by +#! gravity, pushed by forces and by what they meet, and stepped forward in +#! time, as Box2D's world steps them. +#! +#! A step finds the colliders newly near one another, by the boxes of its +#! tree; where those near meet, as contacts kept from the last step; and then +#! solves them, in substeps, as Box2D's soft step does: each substep moves the +#! bodies' velocities by their forces, pushes them apart where they meet, +#! softly so a deep overlap is undone over a few steps rather than at once, +#! moves them, and pushes again without undoing overlaps, so what was pushed +#! apart doesn't fly. Each contact begins a step with the impulses it ended the +#! last with, so a stack settles and stays still. Bodies that rest long enough, +#! with all they touch, sleep until something wakes them. +#! +#! Lengths are a game's units, and its tolerances are made for a unit of a +#! meter: a space of another unit, as pixels, is made with how many units a +#! meter is, so a tolerance of 5 millimeters stays 5 millimeters. + +import std::containers; +import std::math; +import std::time; +import malunal::linear; +module malunal::physics2d; + +#! Where bodies move, as one step after another moves them. +pub struct space { + #! The pull on every dynamic body, in lengths a second each second. + pub var gravity := vec2{ 0, -10 }; + #! How many substeps each step is solved in: more is stiffer and slower. + pub var substeps: u32 = 4; + #! How stiff contacts are, as a spring of so many cycles a second, and how + #! much they're damped: past 1, they don't spring back. + pub var contact_hertz: f32 = 30; + pub var contact_damping: f32 = 10; + #! The same of joints. + pub var joint_hertz: f32 = 60; + pub var joint_damping: f32 = 2; + #! The fastest a contact pushes overlapping bodies apart, in lengths a + #! second. + pub var push_speed: f32 = 3; + #! How fast bodies must meet, in lengths a second, to bounce. + pub var restitution_threshold: f32 = 1; + #! How fast colliders must begin touching, in lengths a second, to be told + #! of as a hit. + pub var hit_speed: f32 = 1; + #! The fastest a body moves, in lengths a second. + pub var max_speed: f32 = 400; + #! Whether bodies at rest sleep. + pub var sleeping: bool = true; + #! Whether dynamic bodies moving fast are swept against what stands still, + #! so they never pass through what's thin. + pub var continuous: bool = true; + #! How many threads each step is solved on, its caller's among them: each + #! color of contacts split between them, so a step gives the same on any + #! number. 1 solves on the caller's alone. + pub var threads: u32 = 1; + var crew: crew; + var found: vector; # Each pair's, found on the crew. + var unit: f32 = 1; + var fast: vector; + var bodies: vector; + var colliders: vector; + var grids: vector; + var free_grids: vector; + var met: vector; + var pairs: vector; + var contacts: vector; + var joints: vector; + var free_bodies: vector; + var free_colliders: vector; + var free_pairs: vector; + var free_contacts: vector; + var free_joints: vector; + var tree: aabb_tree; + var pair_keys: dict; + var moved: vector; # Colliders whose leaves moved. + var near: vector; + var noted: vector; + var struck: vector; + var solver: solver_scratch; + var islands: vector; + #! How long the last step took, and each of its parts. + pub var profile: step_profile; +} + +#! A space of no bodies, pulled by a gravity: `unit` is how many of its lengths +#! a meter is, which its tolerances, push speed, bounce threshold, and top +#! speed are scaled by. +pub def space::new(gravity: vec2 = vec2{ 0, -10 }, unit: f32 = 1): space { + return space{ + gravity = gravity, unit = unit, push_speed = 3 * unit, restitution_threshold = unit, hit_speed = unit, max_speed = 400 * unit, + tree = aabb_tree::new(0.1 * unit), pair_keys = dict::::new(), + }; +} + +# How near two surfaces are taken as touching: what contacts let them overlap +# by, and what they meet at before touching. +val space::slop: f32 { + get => 0.005 * this.unit; +} + +val space::speculative: f32 { + get => 4 * this.slop; +} + +#! How many bodies it holds. +pub val space::body_count: u64 { + get => this.bodies.length - this.free_bodies.length; +} + +#! How many contacts it holds: pairs of shapes near enough to meet. +pub val space::contact_count: u64 { + get => this.contacts.length - this.free_contacts.length; +} + +#! The contacts that began and ended touching in the last step. +pub def space::events(&this): span { + return this.noted.span; +} + +#! Adds a body, of no colliders yet. +pub def space::add(&mut this, made: body): body_id { + var index: u32 = 0; + if this.free_bodies.length > 0 { + index = this.free_bodies[this.free_bodies.length - 1]; + this.free_bodies.truncate(); + } else { + index = this.bodies.length as u32; + this.bodies.append(body_record{}); + } + val generation := this.bodies[index as u64].generation + 1; + this.bodies[index as u64] = body_record{ + kind = made.kind, generation = generation, alive = true, at = made.at, center = made.at.at, + velocity = made.kind == body_kind::static ? vec2::zero : made.velocity, spin = made.kind == body_kind::static ? 0f : made.spin, + linear_damping = made.linear_damping, angular_damping = made.angular_damping, gravity_scale = made.gravity_scale, + gravity = made.gravity, fixed_rotation = made.fixed_rotation, can_sleep = made.can_sleep, bullet = made.bullet, data = made.data, + }; + this.find_mass(index); + return body_id{ index = index, generation = generation }; +} + +#! Whether a body is of it still. +pub def space::has(&this, id: body_id): bool { + return id.index < this.bodies.length as u32 && this.bodies[id.index as u64].alive && this.bodies[id.index as u64].generation == id.generation; +} + +#! Removes a body, its colliders, the contacts they're of, and the joints it's +#! of, waking what it touched. +pub def space::remove(&mut this, id: body_id): void { + return if !this.has(id); + # Those it sleeps with wake, as what held them may be gone. + this.wake_body(id.index); + var c := this.bodies[id.index as u64].colliders; + while c != none { + val next := this.colliders[c as u64].next; + this.drop_collider(c); + c = next; + } + this.drop_joints_of(id.index); + this.bodies[id.index as u64].alive = false; + this.bodies[id.index as u64].colliders = none; + this.bodies[id.index as u64].group = none; + this.free_bodies.append(id.index); +} + +#! Gives a body a collider, its mass summed again of its colliders'. +pub def space::attach(&mut this, to: body_id, made: collider): collider_id { + return collider_id{} if !this.has(to); + return this.attach_record(to, collider_record{ made = made, body = to.index }); +} + +#! Gives a static body a grid's solid cells, as a tilemap's walls, met as +#! boxes, each but the faces it shares with a solid neighbor, so what slides +#! along a floor of many cells slides as along one. Its shape and density are +#! passed over; a grid meets shapes, not another grid. +pub def space::attach_grid(&mut this, to: body_id, cells: grid, made: collider): collider_id { + var held := move(cells); + return collider_id{} if !this.has(to); + var g: u32 = 0; + if this.free_grids.length > 0 { + g = this.free_grids[this.free_grids.length - 1]; + this.free_grids.truncate(); + this.grids[g as u64] = move(held); + } else { + g = this.grids.length as u32; + this.grids.append(move(held)); + } + return this.attach_record(to, collider_record{ made = made, grid = g, body = to.index }); +} + +def space::attach_record(&mut this, to: body_id, record: collider_record): collider_id { + var index: u32 = 0; + if this.free_colliders.length > 0 { + index = this.free_colliders[this.free_colliders.length - 1]; + this.free_colliders.truncate(); + } else { + index = this.colliders.length as u32; + this.colliders.append(collider_record{}); + } + val generation := this.colliders[index as u64].generation + 1; + var made := record; + made.next = this.bodies[to.index as u64].colliders; + made.generation = generation; + made.alive = true; + made.moved = true; + this.colliders[index as u64] = made; + val box := this.box_of(index, this.bodies[to.index as u64].at); + this.colliders[index as u64].leaf = this.tree.insert(box, index as u64); + this.bodies[to.index as u64].colliders = index; + this.moved.append(index); + this.find_mass(to.index); + this.wake_body(to.index); + return collider_id{ index = index, generation = generation }; +} + +# The box holding a collider, where a pose places its body. +def space::box_of(&this, c: u32, at: pose): aabb { + val record := &this.colliders[c as u64]; + return record.made.shape.bounds(at) if !record.is_grid(); + val own := this.grids[record.grid as u64].bounds; + val corners: vec2[4] = [own.min, vec2{ own.max.x, own.min.y }, own.max, vec2{ own.min.x, own.max.y }]; + var low := at.apply(corners[0]); + var high := low; + for k in 1..4u { + val p := at.apply(corners[k]); + low = low.min(p); + high = high.max(p); + } + return aabb{ low, high }; +} + +#! Whether a collider is of it still. +pub def space::has(&this, id: collider_id): bool { + return id.index < this.colliders.length as u32 && this.colliders[id.index as u64].alive && this.colliders[id.index as u64].generation == id.generation; +} + +#! Takes a collider from its body, its mass summed again of the rest. +pub def space::detach(&mut this, id: collider_id): void { + return if !this.has(id); + val b := this.colliders[id.index as u64].body; + # Unlinked from its body's colliders. + var c := this.bodies[b as u64].colliders; + if c == id.index { + this.bodies[b as u64].colliders = this.colliders[c as u64].next; + } else { + while c != none { + val next := this.colliders[c as u64].next; + if next == id.index { + this.colliders[c as u64].next = this.colliders[next as u64].next; + break; + } + c = next; + } + } + this.drop_collider(id.index); + this.find_mass(b); + this.wake_body(b); +} + +# Frees a collider, its leaf, and its pairs. +def space::drop_collider(&mut this, c: u32): void { + for p in 0..this.pairs.length { + if this.pairs[p].alive && (this.pairs[p].a == c || this.pairs[p].b == c) { + this.drop_pair(p as u32, true); + } + } + this.tree.remove(this.colliders[c as u64].leaf); + if this.colliders[c as u64].is_grid() { + val g := this.colliders[c as u64].grid; + this.grids[g as u64] = grid::new(0, 0); + this.free_grids.append(g); + } + this.colliders[c as u64].alive = false; + this.free_colliders.append(c); +} + +#! The body a collider is of. +pub def space::body_of(&this, id: collider_id): body_id { + return body_id{} if !this.has(id); + val b := this.colliders[id.index as u64].body; + return body_id{ index = b, generation = this.bodies[b as u64].generation }; +} + +#! What a collider was made as. +pub def space::collider_of(&this, id: collider_id): &collider { + return &this.colliders[id.index as u64].made; +} + +#! The number its user gave a body. +pub def space::data_of(&this, id: body_id): u64 { + return this.bodies[id.index as u64].data; +} + +#! What kind of body it is. +pub def space::kind_of(&this, id: body_id): body_kind { + return this.bodies[id.index as u64].kind; +} + +#! Where a body is, and which way it's turned. +pub def space::pose_of(&this, id: body_id): pose { + return this.bodies[id.index as u64].at; +} + +#! How fast a body's center of mass moves, and how fast it turns. +pub def space::velocity_of(&this, id: body_id): vec2 { + return this.bodies[id.index as u64].velocity; +} + +pub def space::spin_of(&this, id: body_id): f32 { + return this.bodies[id.index as u64].spin; +} + +#! A body's mass, its center of its own places, and its rotational inertia +#! about that center. +pub def space::mass_of(&this, id: body_id): mass_data { + val b := &this.bodies[id.index as u64]; + return mass_data{ mass = b.mass, center = b.local_center, inertia = b.inertia }; +} + +#! Where a body's center of mass is in the plane. +pub def space::center_of(&this, id: body_id): vec2 { + return this.bodies[id.index as u64].center; +} + +#! Whether a body is awake, as it is but where it and all it rests on have +#! been still long enough. +pub def space::is_awake(&this, id: body_id): bool { + return this.bodies[id.index as u64].awake; +} + +#! Puts a body somewhere, as it is at once, waking it. +pub def space::set_pose(&mut this, id: body_id, at: pose): void { + return if !this.has(id); + this.bodies[id.index as u64].at = at; + this.bodies[id.index as u64].center = at.apply(this.bodies[id.index as u64].local_center); + this.place_colliders(id.index); + this.wake_body(id.index); +} + +#! Sets how fast a body moves, waking it. +pub def space::set_velocity(&mut this, id: body_id, velocity: vec2): void { + return if !this.has(id) || this.bodies[id.index as u64].kind == body_kind::static; + this.bodies[id.index as u64].velocity = velocity; + if velocity.length_squared > 0 { + this.wake_body(id.index); + } +} + +#! Sets how fast a body turns, waking it. +pub def space::set_spin(&mut this, id: body_id, spin: f32): void { + return if !this.has(id) || this.bodies[id.index as u64].kind == body_kind::static || this.bodies[id.index as u64].fixed_rotation; + this.bodies[id.index as u64].spin = spin; + if spin != 0 { + this.wake_body(id.index); + } +} + +#! Sets a body's own gravity, added to the space's, as a planet's pull changes +#! as the body goes around it; waking it where that turns or grows it by more +#! than a hundredth, so a body asleep stays so as the pull is found again. +pub def space::set_gravity(&mut this, id: body_id, gravity: vec2): void { + return if !this.has(id); + val i := id.index as u64; + val was := this.bodies[i].gravity; + this.bodies[i].gravity = gravity; + if (gravity - was).length_squared > 1e-4 * math::max(gravity.length_squared, was.length_squared) { + this.wake_body(id.index); + } +} + +#! A body's own gravity, added to the space's. +pub def space::gravity_of(&this, id: body_id): vec2 { + return this.bodies[id.index as u64].gravity; +} + +#! Pushes a dynamic body through the next step by a force at a place of the +#! plane, which turns it too where that's off its center, waking it. +pub def space::apply_force(&mut this, id: body_id, force: vec2, at: vec2): void { + return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic(); + val i := id.index as u64; + this.bodies[i].force = this.bodies[i].force + force; + this.bodies[i].torque += (at - this.bodies[i].center).cross(force); + this.wake_body(id.index); +} + +#! Pushes a dynamic body through the next step by a force at its center, +#! waking it. +pub def space::apply_force_to_center(&mut this, id: body_id, force: vec2): void { + return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic(); + this.bodies[id.index as u64].force = this.bodies[id.index as u64].force + force; + this.wake_body(id.index); +} + +#! Turns a dynamic body through the next step by a torque, waking it. +pub def space::apply_torque(&mut this, id: body_id, torque: f32): void { + return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic(); + this.bodies[id.index as u64].torque += torque; + this.wake_body(id.index); +} + +#! Changes how fast a dynamic body moves and turns at once, as a blow at a +#! place of the plane does, waking it. +pub def space::apply_impulse(&mut this, id: body_id, impulse: vec2, at: vec2): void { + return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic(); + val i := id.index as u64; + this.bodies[i].velocity = this.bodies[i].velocity + impulse * this.bodies[i].inv_mass; + this.bodies[i].spin += this.bodies[i].inv_inertia * (at - this.bodies[i].center).cross(impulse); + this.wake_body(id.index); +} + +#! Wakes a body, and those it sleeps with. +pub def space::wake(&mut this, id: body_id): void { + if this.has(id) { + this.wake_body(id.index); + } +} + +# Sums a body's mass of its colliders', where it's dynamic, and how far they +# reach from its center. +def space::find_mass(&mut this, b: u32): void { + var sum := mass_data{}; + if this.bodies[b as u64].is_dynamic() { + var c := this.bodies[b as u64].colliders; + while c != none { + val made := &this.colliders[c as u64].made; + if !this.colliders[c as u64].is_grid() && made.density > 0 { + sum = sum.add(made.shape.mass(made.density)); + } + c = this.colliders[c as u64].next; + } + } + var mass: f32 = 0; + var inertia: f32 = 0; + var local := vec2::zero; + if this.bodies[b as u64].is_dynamic() { + # A dynamic body of no mass moves as one of 1. + mass = sum.mass > 0 ? sum.mass : 1f; + local = sum.center; + if sum.inertia > 0 && !this.bodies[b as u64].fixed_rotation { + inertia = sum.inertia; + } + } + var extent: f32 = 0; + var least: f32 = 0; + var c := this.bodies[b as u64].colliders; + while c != none { + val s := &this.colliders[c as u64].made.shape; + if !this.colliders[c as u64].is_grid() { + for i in 0..s.count { + extent = math::max(extent, (s.point(i) - local).length + s.radius); + } + val reach := s.least_reach(); + least = least == 0 ? reach : math::min(least, reach); + } + c = this.colliders[c as u64].next; + } + val i := b as u64; + this.bodies[i].mass = mass; + this.bodies[i].inv_mass = mass > 0 ? 1 / mass : 0f; + this.bodies[i].inertia = inertia; + this.bodies[i].inv_inertia = inertia > 0 ? 1 / inertia : 0f; + this.bodies[i].local_center = local; + this.bodies[i].center = this.bodies[i].at.apply(local); + this.bodies[i].extent = extent; + this.bodies[i].least = least; +} + +# Puts a body's colliders' leaves where it is, each that leaves its grown box +# to find what it newly nears. +def space::place_colliders(&mut this, b: u32): void { + val at := this.bodies[b as u64].at; + var c := this.bodies[b as u64].colliders; + while c != none { + val box := this.box_of(c, at); + if this.tree.move(this.colliders[c as u64].leaf, box) && !this.colliders[c as u64].moved { + this.colliders[c as u64].moved = true; + this.moved.append(c); + } + c = this.colliders[c as u64].next; + } +} + +#! Where a ray met a space's collider: which, of which body, and where. +pub struct space_hit { + pub var collider: collider_id; + pub var body: body_id; + pub var distance: f32; + pub var point: vec2; + pub var normal: vec2; +} + +#! Where a ray first meets a collider on a layer of a mask, sensors passed +#! over, and chains' segments from behind: from a place, along a direction of +#! length 1, as far as `reach`. +pub def space::ray_cast(&this, origin: vec2, direction: vec2, reach: f32, mask: u32 = 0xFFFFFFFF): maybe { + return this.ray_cast(origin, direction, reach, query_filter{ mask = mask }); +} + +#! Where a ray first meets a collider a filter asks of, as `ray_cast` casts +#! it. +pub def space::ray_cast(&this, origin: vec2, direction: vec2, reach: f32, filter: query_filter): maybe { + var best: maybe = nothing{}; + this.tree.ray_cast(origin, direction, reach, def(leaf: u32, data: u64, so_far: f32): f32 { + val c := &this.colliders[data]; + return so_far if !this.passes(data as u32, &filter); + val at := this.bodies[c.body as u64].at; + var met := ray_hit{}; + if c.is_grid() { + val cell := this.grids[c.grid as u64].ray_cast(at, origin, direction, so_far) else { return so_far; }; + met = cell.hit; + } else { + # A chain's segment is met only from its front. + return so_far if c.made.shape.is_one_sided && direction.dot(at.turn.apply(c.made.shape.normal(0))) >= 0; + met = c.made.shape.ray_cast(at, origin, direction, so_far) else { return so_far; }; + } + best = space_hit{ + collider = collider_id{ index = data as u32, generation = c.generation }, + body = body_id{ index = c.body, generation = this.bodies[c.body as u64].generation }, + distance = met.distance, point = met.point, normal = met.normal, + }; + return met.distance; + }); + return best; +} + +#! Steps the space forward in time: finds what's newly near, where it meets, +#! and moves its bodies, pushed apart where they meet. Events of what began +#! and stopped touching are those of this step alone after. +pub def space::step(&mut this, dt: f32): void { + this.noted.clear(); + this.struck.clear(); + return if dt <= 0; + val began := instant::now(); + this.crew.start(this.threads); + this.find_pairs(); + val paired := instant::now(); + this.update_contacts(); + val met := instant::now(); + this.solve(dt); + val solved := instant::now(); + if this.sleeping { + this.sleep_islands(dt); + } + val slept := instant::now(); + this.profile = step_profile{ + pairs = milliseconds(paired - began), contacts = milliseconds(met - paired), + solve = milliseconds(solved - met), sleep = milliseconds(slept - solved), step = milliseconds(slept - began), + }; +} + +#! How long a step took, in milliseconds, and each of its parts: finding what +#! newly nears, where it meets, solving it, and finding what sleeps. +pub struct step_profile { + pub var pairs: f64; + pub var contacts: f64; + pub var solve: f64; + pub var sleep: f64; + pub var step: f64; +} + +def milliseconds(d: duration): f64 { + return d.in_nanoseconds as f64 / 1e6; +} diff --git a/physics2d/tree.sakura b/physics2d/tree.sakura new file mode 100644 index 0000000..9287f50 --- /dev/null +++ b/physics2d/tree.sakura @@ -0,0 +1,340 @@ +#! Contains `aabb_tree`, a tree of boxes: each leaf a box holding a number of +#! its user's, as an entity's bits, and each branch the least box holding its +#! two children, so what's near a box, or along a ray, is found by passing down +#! only the branches that reach it, as Box2D's dynamic tree finds it. +#! +#! A leaf's box is grown past what it holds by the tree's margin, so what moves +#! a little stays within it, and the tree isn't changed. A leaf is put where it +#! grows the boxes above it least, and each branch it passes is turned, as an +#! AVL tree turns one, where one child is two or more deeper than the other, +#! so the tree stays shallow whatever order its leaves come in. + +import std::math; +import malunal::linear; +module malunal::physics2d; + +# No node. +const none_node: u32 = 0xFFFFFFFF; + +# The deepest a tree of shallow branches can be, with room to spare: past 2^40 +# leaves. +const most_depth: u64 = 64; + +struct tree_node { + var box: aabb; + var data: u64; + var parent: u32 = 0xFFFFFFFF; # Or the next free node, where it's free. + var left: u32 = 0xFFFFFFFF; # None of a leaf. + var right: u32 = 0xFFFFFFFF; + var height: i32; # 0 of a leaf, and -1 where it's free. +} + +#! A tree of boxes, each leaf holding a number of its user's, named by the leaf +#! `insert` gives, which stays its name until it's removed. +pub struct aabb_tree { + var nodes: vector; + var root: u32 = 0xFFFFFFFF; + var free: u32 = 0xFFFFFFFF; + var leaves: u64; + #! How far each leaf's box is grown past what it holds. + pub var margin: f32 = 0.1; +} + +#! A tree of no leaves, its boxes grown by a margin. +pub def aabb_tree::new(margin: f32 = 0.1): aabb_tree { + return aabb_tree{ nodes = vector::::new(), margin = margin }; +} + +#! How many leaves it holds. +pub val aabb_tree::length: u64 { + get => this.leaves; +} + +#! How deep it is: 0 of no leaves or one, and 1 more for each branch down to +#! its deepest leaf. +pub val aabb_tree::height: i32 { + get => this.root == none_node ? 0 : this.nodes[this.root as u64].height; +} + +#! Adds a box, and a number of the user's, as a leaf. +#! @returns The leaf, which names it until it's removed. +pub def aabb_tree::insert(&mut this, box: aabb, data: u64): u32 { + val leaf := this.allocate(); + this.nodes[leaf as u64].box = box.grown(this.margin); + this.nodes[leaf as u64].data = data; + this.nodes[leaf as u64].height = 0; + this.insert_leaf(leaf); + this.leaves++; + return leaf; +} + +#! Removes a leaf. +pub def aabb_tree::remove(&mut this, leaf: u32): void { + this.remove_leaf(leaf); + this.release(leaf); + this.leaves--; +} + +#! Moves a leaf to hold a box, where its grown box doesn't hold it already. +#! @returns Whether it was moved. +pub def aabb_tree::move(&mut this, leaf: u32, box: aabb): bool { + return false if this.nodes[leaf as u64].box.encloses(box); + this.remove_leaf(leaf); + this.nodes[leaf as u64].box = box.grown(this.margin); + this.insert_leaf(leaf); + return true; +} + +#! The number a leaf holds. +pub def aabb_tree::data(&this, leaf: u32): u64 { + return this.nodes[leaf as u64].data; +} + +#! A leaf's box, grown by the margin. +pub def aabb_tree::box_of(&this, leaf: u32): aabb { + return this.nodes[leaf as u64].box; +} + +#! Visits each leaf whose box meets a box, as `visit(leaf, data)`, until it +#! gives false. +pub def aabb_tree::query(&this, box: aabb, visit: F): void where F: invokable { + return if this.root == none_node; + var stack: u32[64]; + var top: u64 = 1; + stack[0] = this.root; + while top > 0 { + top--; + val index := stack[top] as u64; + continue if !this.nodes[index].box.overlaps(box); + if this.nodes[index].left == none_node { + return if !visit(index as u32, this.nodes[index].data); + } else if top + 2 <= most_depth { + stack[top] = this.nodes[index].left; + stack[top + 1] = this.nodes[index].right; + top += 2; + } + } +} + +#! Visits each leaf whose box a ray meets, from a place, along a direction of +#! length 1, as far as `reach`, as `visit(leaf, data, reach)`, which gives how +#! far to go on: the distance of what it found there, so only what's nearer is +#! visited after; `reach` as it was, to go on as far; or 0, to stop. +pub def aabb_tree::ray_cast(&this, origin: vec2, direction: vec2, reach: f32, visit: F): void + where F: invokable { + return if this.root == none_node; + var far := reach; + var stack: u32[64]; + var top: u64 = 1; + stack[0] = this.root; + while top > 0 { + top--; + val index := stack[top] as u64; + continue if this.nodes[index].box.ray_hit(origin, direction, far) is none; + if this.nodes[index].left == none_node { + val next := visit(index as u32, this.nodes[index].data, far); + return if next <= 0; + far = math::min(far, next); + } else if top + 2 <= most_depth { + stack[top] = this.nodes[index].left; + stack[top + 1] = this.nodes[index].right; + top += 2; + } + } +} + +#! Whether the tree is as it should be: each node's parent its parent, each +#! branch's box the least holding its children's, and its height one more than +#! its deeper child's, each branch's children no more than one apart in height. +#! For tests. +pub def aabb_tree::is_sound(&this): bool { + return true if this.root == none_node; + return false if this.nodes[this.root as u64].parent != none_node; + var stack: u32[64]; + var top: u64 = 1; + var seen: u64 = 0; + stack[0] = this.root; + while top > 0 { + top--; + val index := stack[top] as u64; + val left := this.nodes[index].left; + val right := this.nodes[index].right; + if left == none_node { + return false if right != none_node || this.nodes[index].height != 0; + seen++; + continue; + } + val l := &this.nodes[left as u64]; + val r := &this.nodes[right as u64]; + return false if l.parent != index as u32 || r.parent != index as u32; + return false if this.nodes[index].height != 1 + math::max(l.height, r.height) || math::abs(l.height - r.height) > 1; + return false if !(l.box.merged(r.box) == this.nodes[index].box); + return false if top + 2 > most_depth; + stack[top] = left; + stack[top + 1] = right; + top += 2; + } + return seen == this.leaves; +} + +# A node to use: a free one, or a new one. +def aabb_tree::allocate(&mut this): u32 { + if this.free == none_node { + this.nodes.append(tree_node{}); + return (this.nodes.length - 1) as u32; + } + val made := this.free; + this.free = this.nodes[made as u64].parent; + this.nodes[made as u64] = tree_node{}; + return made; +} + +# Frees a node, for another to use. +def aabb_tree::release(&mut this, index: u32): void { + this.nodes[index as u64] = tree_node{ parent = this.free, height = -1 }; + this.free = index; +} + +# What putting a box beneath a child costs: what the child's box grows by, or +# all of it, of a leaf, which a new branch takes the place of. +def aabb_tree::descent_cost(&this, child: u32, box: aabb): f32 { + val node := &this.nodes[child as u64]; + val merged := box.merged(node.box).perimeter; + return merged if node.left == none_node; + return merged - node.box.perimeter; +} + +# Puts a leaf where it grows the boxes above it least: beside a node, beneath a +# new branch holding both. +def aabb_tree::insert_leaf(&mut this, leaf: u32): void { + if this.root == none_node { + this.root = leaf; + this.nodes[leaf as u64].parent = none_node; + return; + } + val box := this.nodes[leaf as u64].box; + var index := this.root; + while this.nodes[index as u64].left != none_node { + val node_box := this.nodes[index as u64].box; + val left := this.nodes[index as u64].left; + val right := this.nodes[index as u64].right; + val combined := node_box.merged(box).perimeter; + # Beside this node, a new branch holding both; beneath it, every box + # above grows as this one does. + val here := 2 * combined; + val inherited := 2 * (combined - node_box.perimeter); + val to_left := this.descent_cost(left, box) + inherited; + val to_right := this.descent_cost(right, box) + inherited; + break if here < to_left && here < to_right; + index = to_left < to_right ? left : right; + } + + val sibling := index; + val old_parent := this.nodes[sibling as u64].parent; + val branch := this.allocate(); + this.nodes[branch as u64].parent = old_parent; + this.nodes[branch as u64].box = box.merged(this.nodes[sibling as u64].box); + this.nodes[branch as u64].height = this.nodes[sibling as u64].height + 1; + this.nodes[branch as u64].left = sibling; + this.nodes[branch as u64].right = leaf; + this.nodes[sibling as u64].parent = branch; + this.nodes[leaf as u64].parent = branch; + if old_parent == none_node { + this.root = branch; + } else if this.nodes[old_parent as u64].left == sibling { + this.nodes[old_parent as u64].left = branch; + } else { + this.nodes[old_parent as u64].right = branch; + } + this.refit(this.nodes[leaf as u64].parent); +} + +# Takes a leaf out, its sibling taking its parent's place. +def aabb_tree::remove_leaf(&mut this, leaf: u32): void { + if leaf == this.root { + this.root = none_node; + return; + } + val parent := this.nodes[leaf as u64].parent; + val grandparent := this.nodes[parent as u64].parent; + val sibling := this.nodes[parent as u64].left == leaf ? this.nodes[parent as u64].right : this.nodes[parent as u64].left; + this.nodes[sibling as u64].parent = grandparent; + this.release(parent); + if grandparent == none_node { + this.root = sibling; + return; + } + if this.nodes[grandparent as u64].left == parent { + this.nodes[grandparent as u64].left = sibling; + } else { + this.nodes[grandparent as u64].right = sibling; + } + this.refit(grandparent); +} + +# Walks up from a branch to the root, turning each that's out of balance, and +# making its box and height those of its children again. +def aabb_tree::refit(&mut this, from: u32): void { + var index := from; + while index != none_node { + index = this.balance(index); + val left := this.nodes[index as u64].left; + val right := this.nodes[index as u64].right; + this.nodes[index as u64].height = 1 + math::max(this.nodes[left as u64].height, this.nodes[right as u64].height); + this.nodes[index as u64].box = this.nodes[left as u64].box.merged(this.nodes[right as u64].box); + index = this.nodes[index as u64].parent; + } +} + +# Turns a branch whose children are two or more apart in height: the deeper +# child takes its place, and it takes the deeper child's shallower child. +# @returns The node in its place now. +def aabb_tree::balance(&mut this, a: u32): u32 { + return a if this.nodes[a as u64].left == none_node || this.nodes[a as u64].height < 2; + val b := this.nodes[a as u64].left; + val c := this.nodes[a as u64].right; + val leaning := this.nodes[c as u64].height - this.nodes[b as u64].height; + if leaning > 1 { + this.raise(a, c, b, true); + return c; + } + if leaning < -1 { + this.raise(a, b, c, false); + return b; + } + return a; +} + +# Raises `up`, a child of `a`, into its place: `a` becomes `up`'s first child, +# beside `up`'s deeper child, and takes `up`'s shallower child where `up` was, +# `other` its child still. `on_right` says `up` was `a`'s right child. +def aabb_tree::raise(&mut this, a: u32, up: u32, other: u32, on_right: bool): void { + val f := this.nodes[up as u64].left; + val g := this.nodes[up as u64].right; + # `up` takes `a`'s place beneath its parent. + val above := this.nodes[a as u64].parent; + this.nodes[up as u64].left = a; + this.nodes[up as u64].parent = above; + this.nodes[a as u64].parent = up; + if above == none_node { + this.root = up; + } else if this.nodes[above as u64].left == a { + this.nodes[above as u64].left = up; + } else { + this.nodes[above as u64].right = up; + } + # `up` keeps its deeper child; `a` takes the shallower where `up` was. + val deeper := this.nodes[f as u64].height > this.nodes[g as u64].height ? f : g; + val shallower := deeper == f ? g : f; + this.nodes[up as u64].right = deeper; + if on_right { + this.nodes[a as u64].right = shallower; + } else { + this.nodes[a as u64].left = shallower; + } + this.nodes[shallower as u64].parent = a; + this.nodes[a as u64].box = this.nodes[other as u64].box.merged(this.nodes[shallower as u64].box); + this.nodes[a as u64].height = 1 + math::max(this.nodes[other as u64].height, this.nodes[shallower as u64].height); + this.nodes[up as u64].box = this.nodes[a as u64].box.merged(this.nodes[deeper as u64].box); + this.nodes[up as u64].height = 1 + math::max(this.nodes[a as u64].height, this.nodes[deeper as u64].height); +} diff --git a/physics2d/wide.sakura b/physics2d/wide.sakura new file mode 100644 index 0000000..c927b6d --- /dev/null +++ b/physics2d/wide.sakura @@ -0,0 +1,391 @@ +#! Contains how a space solves its contacts eight at a time, as Box2D's solver +#! does: each step, every contact is given the first of 24 colors none of its +#! dynamic bodies has yet, so no two contacts of a color push the same body, +#! and the contacts of each color are solved as the lanes of `f32x8`s, eight at +#! once, each body's velocities gathered from where its state is and scattered +#! back. What fits no color is solved one at a time after. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics2d; + +# How many colors contacts are sorted into. +const colors: u64 = 24; + +# How many contacts are solved at once, and the vectors of their numbers. +const width: u64 = 8; +type lanes = f32x8; +type lane_places = i32x8; + +# A point of eight contacts, a lane each: where it is from each body's +# center, how far apart they are there but for how far they've moved, and the +# impulses pushing them apart and along. A lane of a contact of one point has +# a second of no mass, which pushes nothing. +struct wide_point { + var rax: lanes; + var ray: lanes; + var rbx: lanes; + var rby: lanes; + var base: lanes; + var normal: lanes; + var tangent: lanes; + var most: lanes; + var normal_mass: lanes; + var tangent_mass: lanes; +} + +# Eight contacts as lanes: where each body's state begins among the states' +# numbers, the normal, friction, each body's inverse mass and inertia, and how +# soft each is. A lane of no contact is of the state of what doesn't move, and +# pushes nothing. +struct wide_contact { + var a: lane_places; + var b: lane_places; + var nx: lanes; + var ny: lanes; + var friction: lanes; + var ma: lanes; + var ia: lanes; + var mb: lanes; + var ib: lanes; + var bias_rate: lanes; + var mass_scale: lanes; + var impulse_scale: lanes; + var points: wide_point[2]; + var of: u32[8]; # Each lane's constraint, or none. +} + +# The states' numbers, eight to a state, as `wide_contact`'s lanes gather them. +def numbers_of(s: &mut solver_scratch): slice { + return slice::::over(s.states.data as *mut f32, s.states.length * 8); +} + +# Sorts the step's contacts into colors, and packs each color's into lanes. +def color_contacts(s: &mut solver_scratch): void { + s.wide.clear(); + s.overflow.clear(); + val words := (s.states.length + 63) / 64; + s.colored.clear(); + s.colored.resize(colors * words, 0); + s.color_of.clear(); + s.color_of.resize(s.constraints.length, none); + var counts: u32[24]; + for k in 0..s.constraints.length { + val c := &s.constraints[k]; + # Only a body that's pushed is a body two lanes mustn't share. + val a := c.ma > 0 || c.ia > 0 ? c.a as u64 : 0u; + val b := c.mb > 0 || c.ib > 0 ? c.b as u64 : 0u; + for color in 0..colors { + val row := color * words; + continue if a != 0 && ((s.colored[row + a / 64] >> (a % 64)) & 1) != 0; + continue if b != 0 && ((s.colored[row + b / 64] >> (b % 64)) & 1) != 0; + if a != 0 { + s.colored[row + a / 64] = s.colored[row + a / 64] | (1u << (a % 64)); + } + if b != 0 { + s.colored[row + b / 64] = s.colored[row + b / 64] | (1u << (b % 64)); + } + s.color_of[k] = color as u32; + counts[color]++; + break; + } + if s.color_of[k] == none { + s.overflow.append(k as u32); + } + } + # Each color's lanes, a group of eight after another. + var first: u32[24]; + var groups: u64 = 0; + for color in 0..colors { + first[color] = groups as u32; + s.color_groups[color] = groups as u32; + groups += (counts[color] as u64 + width - 1) / width; + } + s.color_groups[colors] = groups as u32; + s.wide.resize(groups, wide_contact{}); + for g in 0..groups { + for lane in 0..width { + s.wide[g].of[lane] = none; + } + } + var filled: u32[24]; + for k in 0..s.constraints.length { + val color := s.color_of[k]; + continue if color == none; + val at := filled[color as u64]; + filled[color as u64]++; + pack(&mut s.wide[(first[color as u64] as u64 + at as u64 / width)], at as u64 % width, &s.constraints[k], k as u32); + } + if experiment { + s.overflow.clear(); + for g in 0..s.wide.length { + for lane in 0..width { + if s.wide[g].of[lane] != none { + s.overflow.append(s.wide[g].of[lane]); + } + } + } + s.wide.clear(); + } +} + +const experiment: bool = false; + +# Puts a contact into a lane. +def pack(w: &mut wide_contact, lane: u64, c: &contact_constraint, k: u32): void { + w.of[lane] = k; + w.a[lane] = (c.a * 8) as i32; + w.b[lane] = (c.b * 8) as i32; + w.nx[lane] = c.normal.x; + w.ny[lane] = c.normal.y; + w.friction[lane] = c.friction; + w.ma[lane] = c.ma; + w.ia[lane] = c.ia; + w.mb[lane] = c.mb; + w.ib[lane] = c.ib; + w.bias_rate[lane] = c.soft.bias_rate; + w.mass_scale[lane] = c.soft.mass_scale; + w.impulse_scale[lane] = c.soft.impulse_scale; + for j in 0..c.count { + val p := &c.points[j]; + w.points[j].rax[lane] = p.anchor_a.x; + w.points[j].ray[lane] = p.anchor_a.y; + w.points[j].rbx[lane] = p.anchor_b.x; + w.points[j].rby[lane] = p.anchor_b.y; + w.points[j].base[lane] = p.base_separation; + w.points[j].normal[lane] = p.normal_impulse; + w.points[j].tangent[lane] = p.tangent_impulse; + w.points[j].normal_mass[lane] = p.normal_mass; + w.points[j].tangent_mass[lane] = p.tangent_mass; + } +} + +# Gives each lane's impulses back to its contact, to bounce and keep. +def unpack_contacts(s: &mut solver_scratch): void { + for g in 0..s.wide.length { + for lane in 0..width { + val k := s.wide[g].of[lane]; + continue if k == none; + for j in 0..s.constraints[k as u64].count { + s.constraints[k as u64].points[j].normal_impulse = s.wide[g].points[j].normal[lane]; + s.constraints[k as u64].points[j].tangent_impulse = s.wide[g].points[j].tangent[lane]; + s.constraints[k as u64].points[j].max_impulse = math::max(s.constraints[k as u64].points[j].max_impulse, s.wide[g].points[j].most[lane]); + } + } + } +} + +# A stage of a step's lanes, run on the space's crew a color at a time: the +# lanes of each color split between its threads, as no two lanes of a color +# push one body. +struct wide_job { + var s: *mut solver_scratch; + var first: u64; + var warming: bool; + var inv_h: f32; + var push: f32; + var use_bias: bool; +} + +def run_wide(context: *mut u8, begin: u64, end: u64): void { + val job := &through(context as *mut wide_job); + val s := &mut through(job.s); + if job.warming { + warm_groups(s, job.first + begin, job.first + end); + } else { + solve_groups(s, job.first + begin, job.first + end, job.inv_h, job.push, job.use_bias); + } +} + +# Warms or solves the lanes, on the crew where the space has one, a color at a +# time. +def space::wide_stage(&mut this, s: &mut solver_scratch, warming: bool, inv_h: f32, push: f32, use_bias: bool): void { + if this.threads <= 1 { + if warming { + warm_groups(s, 0, s.wide.length); + } else { + solve_groups(s, 0, s.wide.length, inv_h, push, use_bias); + } + return; + } + var job := wide_job{ s = address(s), warming = warming, inv_h = inv_h, push = push, use_bias = use_bias }; + for color in 0..colors { + val from := s.color_groups[color] as u64; + val to := s.color_groups[color + 1] as u64; + continue if to == from; + job.first = from; + val block := math::max((to - from) / (this.threads as u64 * 4), 1u); + this.crew.run(run_wide, address(&mut job) as *mut u8, to - from, block); + } +} + +# Which lanes push a body, by its inverse mass and inertia: those of what +# doesn't move, or isn't pushed, as a kinematic body, aren't written back, as +# lanes on other threads read its state. +def pushed(m: lanes, i: lanes): bool[8] { + val ms := m.lanes(); + val turns := i.lanes(); + var made: bool[8]; + for k in 0..width { + made[k] = ms[k] > 0 || turns[k] > 0; + } + return made; +} +# Writes each pushed lane's number back to where it was gathered from. +def put(v: lanes, into: slice, at: lane_places, keep: &bool[8]): void { + val each := v.lanes(); + val places := at.lanes(); + for k in 0..width { + if keep[k] { + into[places[k] as u64] = each[k]; + } + } +} +def warm_groups(s: &mut solver_scratch, from: u64, to: u64): void { + val numbers := numbers_of(s); + val view := numbers.span; + val one := lane_places::splat(1); + val two := lane_places::splat(2); + val groups := s.wide.slice; + for g in from..to { + val w := &groups[g]; + val keep_a := pushed(w.ma, w.ia); + val keep_b := pushed(w.mb, w.ib); + val a1 := w.a + one; + val a2 := w.a + two; + val b1 := w.b + one; + val b2 := w.b + two; + var vax := lanes::gather(view, w.a); + var vay := lanes::gather(view, a1); + var wa := lanes::gather(view, a2); + var vbx := lanes::gather(view, w.b); + var vby := lanes::gather(view, b1); + var wb := lanes::gather(view, b2); + val tx := w.ny; + val ty := -w.nx; + for j in 0..2u { + val p := &w.points[j]; + val px := w.nx * p.normal + tx * p.tangent; + val py := w.ny * p.normal + ty * p.tangent; + wa = wa - w.ia * (p.rax * py - p.ray * px); + vax = vax - px * w.ma; + vay = vay - py * w.ma; + wb = wb + w.ib * (p.rbx * py - p.rby * px); + vbx = vbx + px * w.mb; + vby = vby + py * w.mb; + } + put(vax, numbers, w.a, &keep_a); + put(vay, numbers, a1, &keep_a); + put(wa, numbers, a2, &keep_a); + put(vbx, numbers, w.b, &keep_b); + put(vby, numbers, b1, &keep_b); + put(wb, numbers, b2, &keep_b); + } +} + +def solve_groups(s: &mut solver_scratch, from: u64, to: u64, inv_h: f32, push: f32, use_bias: bool): void { + val numbers := numbers_of(s); + val view := numbers.span; + val one := lane_places::splat(1); + val two := lane_places::splat(2); + val four := lane_places::splat(4); + val five := lane_places::splat(5); + val six := lane_places::splat(6); + val seven := lane_places::splat(7); + val zero := lanes::splat(0); + val unit := lanes::splat(1); + val per_h := lanes::splat(inv_h); + val least := lanes::splat(-push); + val groups := s.wide.slice; + for g in from..to { + val w := &mut groups[g]; + val keep_a := pushed(w.ma, w.ia); + val keep_b := pushed(w.mb, w.ib); + val a1 := w.a + one; + val a2 := w.a + two; + val b1 := w.b + one; + val b2 := w.b + two; + var vax := lanes::gather(view, w.a); + var vay := lanes::gather(view, a1); + var wa := lanes::gather(view, a2); + var vbx := lanes::gather(view, w.b); + var vby := lanes::gather(view, b1); + var wb := lanes::gather(view, b2); + val dpx := lanes::gather(view, w.b + four) - lanes::gather(view, w.a + four); + val dpy := lanes::gather(view, w.b + five) - lanes::gather(view, w.a + five); + val qac := lanes::gather(view, w.a + six); + val qas := lanes::gather(view, w.a + seven); + val qbc := lanes::gather(view, w.b + six); + val qbs := lanes::gather(view, w.b + seven); + val nx := w.nx; + val ny := w.ny; + val ma := w.ma; + val ia := w.ia; + val mb := w.mb; + val ib := w.ib; + for j in 0..2u { + val p := &mut w.points[j]; + val rax := p.rax; + val ray := p.ray; + val rbx := p.rbx; + val rby := p.rby; + val dx := dpx + (qbc * rbx - qbs * rby) - (qac * rax - qas * ray); + val dy := dpy + (qbs * rbx + qbc * rby) - (qas * rax + qac * ray); + val separation := dx * nx + dy * ny + p.base; + # Apart, only what closes the gap this substep; else, pushing softly. + val apart := separation.greater(&zero); + var bias := select(apart, separation * per_h, zero); + var mass_scale := unit; + var impulse_scale := zero; + if use_bias { + bias = select(apart, bias, (w.bias_rate * separation).max(&least)); + mass_scale = select(apart, unit, w.mass_scale); + impulse_scale = select(apart, zero, w.impulse_scale); + } + val vn := (vbx - wb * rby - vax + wa * ray) * nx + (vby + wb * rbx - vay - wa * rax) * ny; + val before := p.normal; + val sum := (before - p.normal_mass * mass_scale * (vn + bias) - impulse_scale * before).max(&zero); + val impulse := sum - before; + p.normal = sum; + p.most = p.most.max(&impulse); + val px := nx * impulse; + val py := ny * impulse; + vax = vax - px * ma; + vay = vay - py * ma; + wa = wa - ia * (rax * py - ray * px); + vbx = vbx + px * mb; + vby = vby + py * mb; + wb = wb + ib * (rbx * py - rby * px); + } + val tx := ny; + val ty := -nx; + for j in 0..2u { + val p := &mut w.points[j]; + val rax := p.rax; + val ray := p.ray; + val rbx := p.rbx; + val rby := p.rby; + val vt := (vbx - wb * rby - vax + wa * ray) * tx + (vby + wb * rbx - vay - wa * rax) * ty; + val most := w.friction * p.normal; + val before := p.tangent; + val sum := (before - p.tangent_mass * vt).min(&most).max(&-most); + val impulse := sum - before; + p.tangent = sum; + val px := tx * impulse; + val py := ty * impulse; + vax = vax - px * ma; + vay = vay - py * ma; + wa = wa - ia * (rax * py - ray * px); + vbx = vbx + px * mb; + vby = vby + py * mb; + wb = wb + ib * (rbx * py - rby * px); + } + put(vax, numbers, w.a, &keep_a); + put(vay, numbers, a1, &keep_a); + put(wa, numbers, a2, &keep_a); + put(vbx, numbers, w.b, &keep_b); + put(vby, numbers, b1, &keep_b); + put(wb, numbers, b2, &keep_b); + } +} diff --git a/physics3d/body.sakura b/physics3d/body.sakura new file mode 100644 index 0000000..6156abc --- /dev/null +++ b/physics3d/body.sakura @@ -0,0 +1,151 @@ +#! Contains `body` and `collider`, what a `space` is given to make a body and +#! the shapes it's of, and `body_id` and `collider_id`, which name them there. + +import malunal::linear; +module malunal::physics3d; + +#! What moves a body. +pub enum body_kind: u8 { + #! Nothing: it stays where it's put, as the ground does. + static, + #! Its velocity alone, as it's set: what it meets doesn't push it, as a + #! moving platform's doesn't. + kinematic, + #! Forces, gravity, and what it meets, as a crate. + dynamic, +} + +#! What a body is made as: its kind, its pose, how fast it moves at first, +#! and how it's slowed and pulled. +pub struct body { + pub var kind := body_kind::dynamic; + #! Where its origin is, and which way it's turned; its colliders' shapes are + #! of places about the origin. + pub var at := pose::identity; + #! How fast its center of mass moves, in lengths a second. + pub var velocity: vec3; + #! How fast it turns, about the axis it points along, by its length in + #! radians a second. + pub var spin: vec3; + #! How much of its velocity, and of its spin, it loses each second, as air + #! slows it. + pub var linear_damping: f32; + pub var angular_damping: f32 = 0.05; + #! How much of the space's gravity, and its own, pulls it: 0 floats. + pub var gravity_scale: f32 = 1; + #! A gravity of its own, added to the space's, as a planet's pulls what's + #! near it toward its middle. + pub var gravity: vec3; + #! Whether it never turns, as a character standing up doesn't. + pub var fixed_rotation: bool; + #! Whether it may sleep when it and what it rests on are still. + pub var can_sleep: bool = true; + #! Whether it's swept against moving bodies too, not only what stands + #! still, so it passes through nothing however fast it goes, as a shot. + pub var bullet: bool; + #! A number of its user's, as an entity's bits. + pub var data: u64; +} + +#! What a body's collider is made as: its shape, about the body's origin; its +#! density, which sums to the body's mass; how it slides and bounces; and the +#! layers it's on and meets. A collider of a triangle mesh, which +#! `space::attach_mesh` gives a body, has no shape or density of its own. +pub struct collider { + pub var shape: shape; + #! Its mass for each volume of 1. + pub var density: f32 = 1; + #! How hard it is to slide along: 0 slides freely. Two colliders' are mixed + #! as the square root of their product. + pub var friction: f32 = 0.6; + #! How much of its speed toward what it meets it keeps, bounced back: 0 + #! stops, 1 bounces as high as it fell. Two colliders' greater is taken. + pub var restitution: f32; + #! The layers it's on, and those it meets: two colliders meet where each is + #! on a layer of the other's mask. + pub var layers: u32 = 1; + pub var mask: u32 = 0xFFFFFFFF; + #! Whether it only notes what it overlaps, pushing nothing. + pub var sensor: bool; + #! A number of its user's, as an entity's bits. + pub var data: u64; +} + +#! A body of a space, as `space::add` names it. +pub struct body_id { + pub var index: u32 = 0xFFFFFFFF; + pub var generation: u32; +} + +pub def body_id::equals(&this, other: &body_id): bool { + return this.index == other.index && this.generation == other.generation; +} + +#! A collider of a body of a space, as `space::attach` names it. +pub struct collider_id { + pub var index: u32 = 0xFFFFFFFF; + pub var generation: u32; +} + +pub def collider_id::equals(&this, other: &collider_id): bool { + return this.index == other.index && this.generation == other.generation; +} + +# No body, collider, contact, mesh, or joint. +const none: u32 = 0xFFFFFFFF; + +# A body as the space keeps it. +struct body_record { + var kind: body_kind; + var generation: u32; + var alive: bool; + var at: pose; # Of its origin. + var center: vec3; # Its center of mass, in space. + var local_center: vec3; # The same, of its own places. + var velocity: vec3; + var spin: vec3; + var force: vec3; + var torque: vec3; + var mass: f32; + var inv_mass: f32; + var inertia: mat3; # About its center of mass, of its own axes. + var inv_inertia: mat3; # The same, inverted. + var linear_damping: f32; + var angular_damping: f32; + var gravity_scale: f32 = 1; + var gravity: vec3; # Its own, added to the space's. + var fixed_rotation: bool; + var can_sleep: bool = true; + var awake: bool = true; + var sleep_time: f32; + var extent: f32; # How far its colliders reach from its center. + var least: f32; # How far its narrowest shape reaches from its middle. + var bullet: bool; + var colliders: u32 = 0xFFFFFFFF; + var joints: u32 = 0xFFFFFFFF; + var group: u32 = 0xFFFFFFFF; + var next_in_group: u32 = 0xFFFFFFFF; + var slot: u32; + var data: u64; +} + +# A collider as the space keeps it: of a shape, or of a mesh the space holds. +struct collider_record { + var made: collider; + var mesh: u32 = 0xFFFFFFFF; + var body: u32; + var leaf: u32 = 0xFFFFFFFF; + var next: u32 = 0xFFFFFFFF; + var generation: u32; + var alive: bool; + var moved: bool; +} + +def body_record::is_dynamic(&this): bool { + return this.kind == body_kind::dynamic; +} + +# Whether a collider is of a mesh. +def collider_record::is_mesh(&this): bool { + return this.mesh != none; +} diff --git a/physics3d/character.sakura b/physics3d/character.sakura new file mode 100644 index 0000000..e915601 --- /dev/null +++ b/physics3d/character.sakura @@ -0,0 +1,216 @@ +#! Contains `character`, a body a game walks, as Jolt's virtual character is: +#! not a rigid body of the space, but a shape moved through it by casts, sliding +#! along what it meets, stepping up what's low enough, sticking to the ground as +#! it walks down slopes and off steps, riding what it stands on as that moves, +#! pushed out of what moves into it, and pushing what's dynamic before it. + +import std::math; +import malunal::linear; +module malunal::physics3d; + +#! A character's body, and what it stands on, as its last move found it. +pub struct character { + #! Its shape, about its origin, a capsule standing up as `shape::pill` + #! makes one. + pub var shape := shape::pill(0.6, 1.8); + #! Where its origin is. + pub var at: vec3; + #! Which way is up, against gravity, of length 1: its shape stands along + #! it, as on a planet, where up is away from the middle. + pub var up := vec3::up; + #! How fast it moved in its last move, but for what it rode: what it was + #! asked to, less what it met. A game adds gravity to it while it's in the + #! air. + pub var velocity: vec3; + #! The steepest ground it stands on and walks up, in radians from flat. + pub var max_slope: f32 = 0.8; + #! The highest it steps up, as onto a stair, and the furthest down it keeps + #! to the ground, as walking down one. + pub var step_height: f32 = 0.35; + pub var snap: f32 = 0.35; + #! How far it keeps from what it meets. + pub var skin: f32 = 0.02; + #! Its mass, and the most force it pushes what's dynamic with. + pub var mass: f32 = 70; + pub var push: f32 = 500; + #! The layers of colliders it meets. + pub var mask: u32 = 0xFFFFFFFF; + #! A body of its own in the space, as a kinematic one moved with it so what + #! moves meets it, which it passes over. + pub var body: body_id; + #! Whether it stands on ground it may, and that ground: which way it faces, + #! its body, and how fast it moves where the character stands. + pub var grounded: bool; + pub var ground_normal := vec3::up; + pub var ground: body_id; + pub var ground_velocity: vec3; +} + +#! Whether a character may stand on ground facing a direction. +pub def character::walkable(&this, normal: vec3): bool { + return normal.dot(this.up) >= math::cos(this.max_slope); +} + +#! Its pose: at its place, turned from standing along y to stand along its up. +pub def character::pose(&this): pose { + return this.pose_at(this.at); +} + +# Its pose, were it somewhere else. +def character::pose_at(&this, at: vec3): pose { + return pose::of(at, quat::between(vec3::up, this.up)); +} + +#! Moves a character through a step of `dt` seconds, at a velocity, as its +#! game asks, adding how fast what it stands on moves: pushed out of what it +#! overlaps, then cast along its motion, sliding along what it meets, stepping +#! up what's low enough while it's on the ground, and kept to the ground as it +#! walks down. Its velocity after is what it was asked, less what it met; what +#! it stands on is found again. +pub def space::move_character(&mut this, c: &mut character, velocity: vec3, dt: f32): void { + return if dt <= 0; + val was_grounded := c.grounded; + c.velocity = velocity; + this.push_character_out(c); + var motion := velocity * dt; + if was_grounded { + motion = motion + c.ground_velocity * dt; + } + for iteration in 0..4u { + if motion.length_squared < tiny * tiny { + break; + } + val hit := this.shape_cast(&c.shape, c.pose(), motion, c.mask, c.body) else { + c.at = c.at + motion; + break; + }; + c.at = c.at + motion * hit.fraction + hit.normal * c.skin; + var left := motion * (1 - hit.fraction); + val walkable := c.walkable(hit.normal); + if !walkable && was_grounded && this.step_up(c, velocity * dt) { + break; + } + # What's left slides along what it met: along a wall it can't walk up, + # not up it. + var n := hit.normal; + if !walkable && was_grounded { + val flat := n - c.up * n.dot(c.up); + if flat.length_squared > tiny { + n = flat.normalized(); + } + } + this.push_struck(c, &hit, dt); + left = left - n * math::min(left.dot(n), 0f); + c.velocity = c.velocity - n * math::min(c.velocity.dot(n), 0f); + motion = left; + } + # Kept to the ground walking down a slope or off a step, where it isn't + # moving up. + if was_grounded && c.velocity.dot(c.up) <= 0 && c.snap > 0 { + if this.shape_cast(&c.shape, c.pose(), c.up * -c.snap, c.mask, c.body) is some(down) { + if c.walkable(down.normal) { + c.at = c.at - c.up * (c.snap * down.fraction) + c.up * c.skin; + } + } + } + this.find_ground(c); +} + +# Finds what a character stands on, just below it. +def space::find_ground(&this, c: &mut character): void { + c.grounded = false; + c.ground = body_id{}; + c.ground_velocity = vec3::zero; + val below := this.shape_cast(&c.shape, c.pose(), c.up * (-3 * c.skin), c.mask, c.body) else { return; }; + return if !c.walkable(below.normal); + c.grounded = true; + c.ground_normal = below.normal; + c.ground = below.body; + val b := &this.bodies[below.body.index as u64]; + if b.kind != body_kind::static { + c.ground_velocity = b.velocity + b.spin.cross(c.at - b.center); + } + # Standing, it doesn't fall into the ground. + val falling := c.velocity.dot(c.up); + if falling < 0 { + c.velocity = c.velocity - c.up * falling; + } +} + +# Steps a character up onto what it walked into, where it's no higher than its +# step: raised, moved on as far as it walks this step, and lowered, where +# feeling further ahead finds ground it may stand on there. +def space::step_up(&this, c: &mut character, left: vec3): bool { + val ahead := left - c.up * left.dot(c.up); + return false if ahead.length_squared < tiny * tiny || c.step_height <= 0; + var rise := c.step_height; + if this.shape_cast(&c.shape, c.pose(), c.up * c.step_height, c.mask, c.body) is some(above) { + rise = math::max(c.step_height * above.fraction - c.skin, 0f); + } + return false if rise <= c.skin; + val raised := c.pose_at(c.at + c.up * rise); + # Felt for further ahead than its round foot reaches, however little it's + # left to move, so it steps only onto what's there to stand on, higher than + # it stands, and not onto the step's edge. + val reach := math::max(ahead.length, c.shape.radius + 2 * c.skin); + val probe := ahead.normalized() * reach; + var moved := probe; + if this.shape_cast(&c.shape, raised, probe, c.mask, c.body) is some(wall) { + moved = probe * wall.fraction; + } + return false if moved.length < 0.5 * reach; + val drop := c.up * -(rise + c.skin); + val landing := this.shape_cast(&c.shape, c.pose_at(raised.at + moved), drop, c.mask, c.body) else { return false; }; + return false if !c.walkable(landing.normal) || landing.fraction == 0; + return false if (rise + c.skin) * (1 - landing.fraction) <= c.skin; + # Then moved as far as it walks, and set down, on the step's edge, maybe, to + # walk on from. + val over := c.pose_at(raised.at + ahead * math::min(1f, moved.length / ahead.length)); + val down := this.shape_cast(&c.shape, over, drop, c.mask, c.body) else { return false; }; + c.at = over.at + drop * down.fraction + c.up * c.skin; + return true; +} + +# Pushes a character out of what it overlaps, as what moves into it does, a +# few times over, by the deepest each time. +def space::push_character_out(&this, c: &mut character): void { + for iteration in 0..4u { + var deepest: f32 = 0; + var away := vec3::zero; + val placed := c.pose(); + this.tree.query(grown(c.shape.bounds(placed), c.skin), def(leaf: u32, data: u64): bool { + return true if this.colliders[data].body == c.body.index || !this.passes(data as u32, &query_filter{ mask = c.mask }); + val held := &this.colliders[data]; + val at := this.bodies[held.body as u64].at; + if held.is_mesh() { + this.meshes[held.mesh as u64].collide(at, &c.shape, placed, 0, def(t: u32, m: manifold): bool { + if m.depth > deepest { + deepest = m.depth; + away = m.normal; + } + return true; + }); + return true; + } + val m := collide(&held.made.shape, at, &c.shape, placed) else { return true; }; + if m.depth > deepest { + deepest = m.depth; + away = m.normal; + } + return true; + }); + if deepest <= 0 { + return; + } + c.at = c.at + away * (deepest + c.skin); + } +} + +# Pushes a dynamic body a character walked into, by no more than its push. +def space::push_struck(&mut this, c: &character, hit: &space_cast, dt: f32): void { + return if !this.has(hit.body) || this.bodies[hit.body.index as u64].kind != body_kind::dynamic; + val into := -c.velocity.dot(hit.normal); + return if into <= 0; + val impulse := math::min(into * c.mass, c.push * dt); + this.apply_impulse(hit.body, -hit.normal * impulse, hit.point); +} diff --git a/physics3d/collide.sakura b/physics3d/collide.sakura new file mode 100644 index 0000000..773ca0b --- /dev/null +++ b/physics3d/collide.sakura @@ -0,0 +1,707 @@ +#! Contains collision between shapes: whether two meet, where they're placed, +#! and the `manifold` of where and how deep, which way to push them apart. +#! +#! Each shape is taken as a core, with its radius around it: a sphere's a +#! place, a capsule's a segment, and a hull itself, of no radius. Two spheres +#! or capsules meet as their cores near, a capsule lying along another at two +#! points. A sphere or capsule and a hull meet as the core nears the hull's +#! surface, a capsule lying along a face at two points; or, where the core +#! passes within the hull, by the face or edge that holds them furthest apart, +#! as the separating axis theorem finds it. Two hulls meet by the face of +#! either, or the pair of edges, one of each, that holds them furthest apart, +#! edges only where they make a face of the hulls' Minkowski difference, as +#! Gregorius tests them; at a face, the other's face most against it is +#! clipped to it, at as many as four points, and at two edges, at one. + +import std::math; +import malunal::linear; +module malunal::physics3d; + +#! The most points a manifold holds. +pub const max_contacts: u32 = 4; + +#! A point where two shapes meet: midway between their surfaces, how deep the +#! one is within the other there, 0 where they touch, and which of their +#! features met there, the same from one step to the next while they still +#! meet so, by which a solver carries over what it found. +pub struct contact { + pub var point: vec3; + pub var depth: f32; + pub var id: u32; +} + +#! Where and how deep two shapes meet: the normal from the first toward the +#! second, along which the second is pushed out of the first, and one to four +#! points, as a box resting flat on another rests on four. +pub struct manifold { + pub var normal: vec3; + pub var points: contact[4]; + pub var count: u32; +} + +#! The deepest of its points. +pub val manifold::depth: f32 { + get => this.deepest(); +} + +def manifold::deepest(&this): f32 { + var most := this.count == 0 ? 0f : this.points[0].depth; + for i in 1..this.count { + most = math::max(most, this.points[i].depth); + } + return most; +} + +#! The manifold turned around, of the second shape against the first. +pub def manifold::flipped(&this): manifold { + return manifold{ normal = -this.normal, points = this.points, count = this.count }; +} + +#! Where two shapes meet, each where its pose places it, or nothing where they +#! don't: the manifold's normal from the first toward the second. Within a +#! `margin`, shapes apart are given points too, of depths below 0, as far as +#! they're apart, as a solver keeps what's about to meet from passing through. +pub def collide(a: &shape, at_a: pose, b: &shape, at_b: pose, margin: f32 = 0): maybe { + if a.kind != shape_kind::hull && b.kind == shape_kind::hull { + if collide(b, at_b, a, at_a, margin) is some(m) { + return m.flipped(); + } + return nothing{}; + } + # Everything is worked out as the first shape sees it, then placed. + val rel := at_a.unapply_pose(at_b); + var found: maybe = nothing{}; + if a.kind != shape_kind::hull { + found = cores(a.a, a.b, a.radius, rel.apply(b.a), rel.apply(b.b), b.radius, margin); + } else if b.kind != shape_kind::hull { + found = hull_and_core(a.as_hull(), rel.apply(b.a), rel.apply(b.b), b.radius, margin); + } else { + found = hulls(a.as_hull(), b.as_hull(), &rel, margin); + } + if found is some(m) { + return placed(m, &at_a); + } + return nothing{}; +} + +#! Whether two shapes meet, each where its pose places it, touching among it. +pub def overlaps(a: &shape, at_a: pose, b: &shape, at_b: pose): bool { + return collide(a, at_a, b, at_b) is some(_); +} + +# A manifold of a shape's own places, in space, where a pose places the shape. +def placed(m: manifold, at: &pose): manifold { + val turn := mat3::rotation(at.turn); + var made := manifold{ normal = turn * m.normal, count = m.count }; + for i in 0..m.count { + made.points[i] = contact{ point = at.at + turn * m.points[i].point, depth = m.points[i].depth, id = m.points[i].id }; + } + return made; +} + +# A manifold of one point, between the surfaces of the first, at `on_a` +# within `radius_a` of it along the normal, and the second's, at `on_b` less +# `radius_b`. +def one_point(normal: vec3, on_a: vec3, radius_a: f32, on_b: vec3, radius_b: f32, depth: f32, id: u32): manifold { + var made := manifold{ normal = normal, count = 1 }; + made.points[0] = contact{ point = ((on_a + normal * radius_a) + (on_b - normal * radius_b)) * 0.5, depth = depth, id = id }; + return made; +} + +# Two spheres or capsules, by their cores, each a segment, a sphere's of one +# place. +def cores(a1: vec3, a2: vec3, ra: f32, b1: vec3, b2: vec3, rb: f32, margin: f32): maybe { + val reach := ra + rb; + val pair := nearest_of_segments(a1, a2, b1, b2); + val between := pair[1] - pair[0]; + val distance := between.length; + return nothing{} if distance > reach + margin; + val da := a2 - a1; + val db := b2 - b1; + var normal := vec3::up; + if distance > tiny { + normal = between * (1 / distance); + } else { + # Their cores cross: apart along what's at right angles to both, or to + # either, from the first's middle toward the second's. + var across := da.cross(db); + if across.length_squared <= tiny { + across = da.length_squared > tiny ? perpendicular_to(da.normalized()) : db.length_squared > tiny ? perpendicular_to(db.normalized()) : vec3::up; + } + normal = across.normalized(); + if normal.dot((b1 + b2) * 0.5 - (a1 + a2) * 0.5) < 0 { + normal = -normal; + } + } + # Two capsules lying along one another meet at the ends of what of the + # second lies beside the first. + val la := da.length_squared; + if la > tiny && db.length_squared > tiny && math::abs(da.normalized().dot(db.normalized())) > 0.99 { + val s1 := (b1 - a1).dot(da) / la; + val s2 := (b2 - a1).dot(da) / la; + var low: f32 = 0; + var high: f32 = 1; + if math::abs(s2 - s1) > tiny { + val u0 := -s1 / (s2 - s1); + val u1 := (1 - s1) / (s2 - s1); + low = math::max(0f, math::min(u0, u1)); + high = math::min(1f, math::max(u0, u1)); + } + if high - low > 1e-3 { + var made := manifold{ normal = normal }; + val ends: f32[2] = [low, high]; + for k in 0..2u { + val q := b1 + db * ends[k]; + val p := nearest_on_segment(q, a1, a2); + val s := (q - p).dot(normal); + continue if s > reach + margin; + made.points[made.count] = contact{ point = ((p + normal * ra) + (q - normal * rb)) * 0.5, depth = reach - s, id = k as u32 }; + made.count++; + } + return made if made.count == 2; + } + } + return one_point(normal, pair[0], ra, pair[1], rb, reach - distance, 0); +} + +# A hull and a sphere or capsule, by its core, a segment, a sphere's of one +# place. +def hull_and_core(h: &hull, b1: vec3, b2: vec3, rb: f32, margin: f32): maybe { + val point := (b2 - b1).length_squared <= tiny * tiny; + # Whether the core passes within the hull: the part of it within each + # face's side, as Cyrus and Beck clip a line. + val d := b2 - b1; + var low: f32 = 0; + var high: f32 = 1; + for f in 0..h.faces { + val out := h.normal(f).dot(b1) - h.offset(f); + val rate := h.normal(f).dot(d); + if math::abs(rate) <= tiny { + if out > 0 { + high = -1; + break; + } + continue; + } + val t := -out / rate; + if rate < 0 { + low = math::max(low, t); + } else { + high = math::min(high, t); + } + break if low > high; + } + return core_within(h, b1, b2, point, rb, margin) if low <= high; + + # Apart: the nearest of the hull to either end, or of its edges to the + # segment. + var best := 1e30f; + var on_hull := b1; + var on_core := b1; + val ends: vec3[2] = [b1, b2]; + for k in 0..(point ? 1u : 2u) { + val near := nearest_on_hull(h, ends[k]); + val d2 := (ends[k] - near).length_squared; + if d2 < best { + best = d2; + on_hull = near; + on_core = ends[k]; + } + } + if !point { + for e in 0..h.edges { + val corners := h.edge(e); + val pair := nearest_of_segments(h.point(corners[0]), h.point(corners[1]), b1, b2); + val d2 := (pair[1] - pair[0]).length_squared; + if d2 < best { + best = d2; + on_hull = pair[0]; + on_core = pair[1]; + } + } + } + val distance := math::sqrt(best); + return nothing{} if distance > rb + margin; + return core_within(h, b1, b2, point, rb, margin) if distance <= tiny; + val normal := (on_core - on_hull) * (1 / distance); + if !point { + # Lying along a face, it meets it where it lies over it, at two points. + val face := most_facing(h, normal); + if h.normal(face).dot(normal) > 0.995 { + val along := face_contacts(h, face, b1, b2, rb, margin); + return along if along.count > 0; + } + } + return one_point(normal, on_hull, 0, on_core, rb, rb - distance, 0); +} + +# A core passing within a hull: apart along the hull's face, or the axis at +# right angles to an edge of the hull and the segment, holding them furthest +# apart. +def core_within(h: &hull, b1: vec3, b2: vec3, point: bool, rb: f32, margin: f32): maybe { + var face: u32 = 0; + var face_apart := -1e30f; + for f in 0..h.faces { + val n := h.normal(f); + val s := math::min(n.dot(b1), n.dot(b2)) - h.offset(f); + if s > face_apart { + face_apart = s; + face = f; + } + } + var edge: u32 = 0; + var edge_apart := -1e30f; + var axis := vec3::zero; + if !point { + val db := b2 - b1; + for e in 0..h.edges { + val corners := h.edge(e); + val ea := h.point(corners[0]); + var l := (h.point(corners[1]) - ea).cross(db); + continue if l.length_squared <= tiny; + l = l.normalized(); + if l.dot(ea - h.center) < 0 { + l = -l; + } + val s := math::min(l.dot(b1), l.dot(b2)) - h.point(h.support(l)).dot(l); + if s > edge_apart { + edge_apart = s; + edge = e; + axis = l; + } + } + } + if better_edge(edge_apart, face_apart) { + val corners := h.edge(edge); + val pair := nearest_of_segments(h.point(corners[0]), h.point(corners[1]), b1, b2); + return one_point(axis, pair[0], 0, pair[1], rb, rb - edge_apart, 0x80000000 | edge); + } + val n := h.normal(face); + if !point { + val along := face_contacts(h, face, b1, b2, rb, margin); + return along if along.count > 0; + } + # The deepest end, pushed out by the face. + val q := n.dot(b1) <= n.dot(b2) ? b1 : b2; + val s := n.dot(q) - h.offset(face); + return one_point(n, q - n * s, 0, q, rb, rb - s, 0); +} + +# The face whose normal is most along a direction. +def most_facing(h: &hull, direction: vec3): u32 { + var found: u32 = 0; + var most := -2f; + for f in 0..h.faces { + val d := h.normal(f).dot(direction); + if d > most { + most = d; + found = f; + } + } + return found; +} + +# The hull's place nearest a place outside it: on a face it's in front of, +# where it lies over the face, else on one of the face's edges. +def nearest_on_hull(h: &hull, q: vec3): vec3 { + var best := 1e30f; + var found := q; + for f in 0..h.faces { + val n := h.normal(f); + val s := n.dot(q) - h.offset(f); + continue if s <= 0; + val on_plane := q - n * s; + if within_face(h, f, on_plane) { + if s * s < best { + best = s * s; + found = on_plane; + } + continue; + } + val size := h.face_size(f); + for k in 0..size { + val p := nearest_on_segment(q, h.point(h.corner(f, k)), h.point(h.corner(f, (k + 1) % size))); + val d2 := (q - p).length_squared; + if d2 < best { + best = d2; + found = p; + } + } + } + return found; +} + +# Whether a place in a face's plane lies within its edges. +def within_face(h: &hull, f: u32, p: vec3): bool { + val n := h.normal(f); + val size := h.face_size(f); + for k in 0..size { + val a := h.point(h.corner(f, k)); + val b := h.point(h.corner(f, (k + 1) % size)); + return false if (b - a).cross(p - a).dot(n) < 0; + } + return true; +} + +# A segment clipped to a hull's face, where it lies over it: each end left +# within reach of the face a point. +def face_contacts(h: &hull, face: u32, b1: vec3, b2: vec3, rb: f32, margin: f32): manifold { + val n := h.normal(face); + var ends: vec3[2] = [b1, b2]; + var made := manifold{ normal = n }; + val size := h.face_size(face); + for k in 0..size { + val a := h.point(h.corner(face, k)); + val b := h.point(h.corner(face, (k + 1) % size)); + val side := (b - a).cross(n); + return made if !clip_segment(&mut ends, side, side.dot(a)); + } + val offset := h.offset(face); + for k in 0..2u { + val q := ends[k]; + val s := n.dot(q) - offset; + continue if s > rb + margin; + made.points[made.count] = contact{ point = ((q - n * s) + (q - n * rb)) * 0.5, depth = rb - s, id = k as u32 }; + made.count++; + } + return made; +} + +# Clips a segment to the side of a plane where `normal.dot(p) <= offset`, as +# Sutherland and Hodgman clip: false where none of it is there. +def clip_segment(ends: &mut vec3[2], normal: vec3, offset: f32): bool { + val d0 := normal.dot(ends[0]) - offset; + val d1 := normal.dot(ends[1]) - offset; + return true if d0 <= 0 && d1 <= 0; + return false if d0 > 0 && d1 > 0; + val crossing := ends[0] + (ends[1] - ends[0]) * (d0 / (d0 - d1)); + if d0 > 0 { + ends[0] = crossing; + } else { + ends[1] = crossing; + } + return true; +} + +# Whether two edges' arcs on the sphere of directions cross, so the edge +# between faces `a` and `b` of one hull and that between `c` and `d` of the +# other, its normals turned around, make a face of their Minkowski +# difference, as Gregorius tests it: the only pairs of edges whose axis is a +# separating axis worth testing. +def minkowski_face(a: vec3, b: vec3, c: vec3, d: vec3): bool { + val bxa := b.cross(a); + val dxc := d.cross(c); + val cba := c.dot(bxa); + val dba := d.dot(bxa); + val adc := a.dot(dxc); + val bdc := b.dot(dxc); + return cba * dba < 0 && adc * bdc < 0 && cba * bdc > 0; +} + +# Whether a separation is better than another by enough to be taken over it, +# so the same pair is met the same way from one step to the next: a face of +# the second hull's over the first's by a millimeter and 2 percent, and an +# edge's over a face's by a millimeter and 5, as an edge's point moves more as +# they turn. +def better(separation: f32, than: f32): bool { + return separation > than + 1e-3 + 0.02 * math::abs(than); +} + +def better_edge(separation: f32, than: f32): bool { + return separation > than + 1e-3 + 0.05 * math::abs(than); +} + +# Two hulls, the second placed in the first's places by `rel`. +def hulls(a: &hull, b: &hull, rel: &pose, margin: f32): maybe { + val turn := mat3::rotation(rel.turn); + var bp: vec3[32]; + var bn: vec3[60]; + for i in 0..b.count { + bp[i] = rel.at + turn * b.point(i); + } + for f in 0..b.faces { + bn[f] = turn * b.normal(f); + } + val b_center := rel.at + turn * b.center; + + # The faces of the first. + var face_a: u32 = 0; + var apart_a := -1e30f; + for f in 0..a.faces { + val n := a.normal(f); + var least := 1e30f; + for j in 0..b.count { + least = math::min(least, n.dot(bp[j])); + } + val s := least - a.offset(f); + if s > apart_a { + apart_a = s; + face_a = f; + } + } + return nothing{} if apart_a > margin; + # The faces of the second. + var face_b: u32 = 0; + var apart_b := -1e30f; + for f in 0..b.faces { + val n := bn[f]; + val offset := n.dot(bp[b.corner(f, 0)]); + var least := 1e30f; + for i in 0..a.count { + least = math::min(least, n.dot(a.point(i))); + } + val s := least - offset; + if s > apart_b { + apart_b = s; + face_b = f; + } + } + return nothing{} if apart_b > margin; + # Pairs of edges, one of each. + val flat := a.is_flat || b.is_flat; + var edge_a: u32 = 0; + var edge_b: u32 = 0; + var apart_e := -1e30f; + var axis := vec3::zero; + for ea in 0..a.edges { + val ac := a.edge(ea); + val p1 := a.point(ac[0]); + val da := a.point(ac[1]) - p1; + val af := a.edge_faces(ea); + for eb in 0..b.edges { + # Only pairs whose arcs of the Gauss map cross make a face of the + # Minkowski difference, which is cheaper to ask than the axis is to find. + if !flat { + val bf := b.edge_faces(eb); + continue if !minkowski_face(a.normal(af[0]), a.normal(af[1]), -bn[bf[0]], -bn[bf[1]]); + } + val bc := b.edge(eb); + val q1 := bp[bc[0]]; + val db := bp[bc[1]] - q1; + var l := da.cross(db); + val length := l.length; + continue if length <= 1e-4 * math::sqrt(da.length_squared * db.length_squared); + l = l * (1 / length); + var s: f32 = 0; + if flat { + # A flat hull's edges meet the other's anywhere, so each axis is + # tested by how far the hulls reach along it, either way. + var a_low := 1e30f; + var a_high := -1e30f; + for i in 0..a.count { + val x := l.dot(a.point(i)); + a_low = math::min(a_low, x); + a_high = math::max(a_high, x); + } + var b_low := 1e30f; + var b_high := -1e30f; + for j in 0..b.count { + val x := l.dot(bp[j]); + b_low = math::min(b_low, x); + b_high = math::max(b_high, x); + } + s = b_low - a_high; + if a_low - b_high > s { + s = a_low - b_high; + l = -l; + } + } else { + if l.dot(p1 - a.center) < 0 { + l = -l; + } + s = l.dot(q1 - p1); + } + if s > apart_e { + apart_e = s; + edge_a = ea; + edge_b = eb; + axis = l; + } + } + } + return nothing{} if apart_e > margin; + + val apart_face := math::max(apart_a, apart_b); + if better_edge(apart_e, apart_face) { + val ac := a.edge(edge_a); + val bc := b.edge(edge_b); + val pair := nearest_of_segments(a.point(ac[0]), a.point(ac[1]), bp[bc[0]], bp[bc[1]]); + return one_point(axis, pair[0], 0, pair[1], 0, -apart_e, 0x80000000 | (edge_a << 8) | edge_b); + } + return clipped(a, b, &bp, &bn, face_a, face_b, better(apart_b, apart_a), margin); +} + +# The face of the other hull most against the reference face, clipped to the +# reference face's sides: each corner left within the margin of the reference +# face a point, as many as four kept. +def clipped(a: &hull, b: &hull, bp: &vec3[32], bn: &vec3[60], face_a: u32, face_b: u32, flip: bool, margin: f32): maybe { + # The reference face's corners and normal, and the incident face's corners. + var reference: vec3[32]; + var size: u32 = 0; + var n := vec3::zero; + var polygon: vec3[64]; + var ids: u32[64]; + var count: u32 = 0; + var incident: u32 = 0; + if !flip { + n = a.normal(face_a); + size = a.face_size(face_a); + for k in 0..size { + reference[k] = a.point(a.corner(face_a, k)); + } + var least := 2f; + for f in 0..b.faces { + val d := bn[f].dot(n); + if d < least { + least = d; + incident = f; + } + } + count = b.face_size(incident); + for k in 0..count { + polygon[k] = bp[b.corner(incident, k)]; + ids[k] = k; + } + } else { + n = bn[face_b]; + size = b.face_size(face_b); + for k in 0..size { + reference[k] = bp[b.corner(face_b, k)]; + } + var least := 2f; + for f in 0..a.faces { + val d := a.normal(f).dot(n); + if d < least { + least = d; + incident = f; + } + } + count = a.face_size(incident); + for k in 0..count { + polygon[k] = a.point(a.corner(incident, k)); + ids[k] = k; + } + } + # The faces met, in the high bits of each point's id. + val flipped: u32 = flip ? 0x40000000 : 0; + val tag := flipped | ((flip ? face_b : face_a) << 22) | (incident << 16); + + # Clipped by the plane through each edge of the reference face, at right + # angles to it. + var next: vec3[64]; + var next_ids: u32[64]; + for k in 0..size { + val from := reference[k]; + val side := (reference[(k + 1) % size] - from).cross(n); + val offset := side.dot(from); + var made: u32 = 0; + for i in 0..count { + val p := polygon[i]; + val q := polygon[(i + 1) % count]; + val dp := side.dot(p) - offset; + val dq := side.dot(q) - offset; + if dp <= 0 && made < 64 { + next[made] = p; + next_ids[made] = ids[i]; + made++; + } + if (dp <= 0) != (dq <= 0) && made < 64 { + next[made] = p + (q - p) * (dp / (dp - dq)); + next_ids[made] = ((k + 1) << 8) | i; + made++; + } + } + count = made; + for i in 0..count { + polygon[i] = next[i]; + ids[i] = next_ids[i]; + } + break if count == 0; + } + + # What's within the margin of the reference face, midway between it and + # the incident face. + val offset := n.dot(reference[0]); + var found: contact[64]; + var kept: u32 = 0; + for i in 0..count { + val s := n.dot(polygon[i]) - offset; + continue if s > margin; + found[kept] = contact{ point = polygon[i] - n * (s * 0.5), depth = -s, id = tag | ids[i] }; + kept++; + } + return nothing{} if kept == 0; + var made := manifold{ normal = flip ? -n : n }; + if kept <= max_contacts { + for i in 0..kept { + made.points[i] = found[i]; + } + made.count = kept; + return made; + } + return reduced(&found, kept, n, made); +} + +# Four of many points, holding the most of the area they hold: the deepest, +# the one furthest from it, the one making the largest triangle of those, and +# the one adding the most to the triangle. +def reduced(found: &contact[64], count: u32, n: vec3, into: manifold): manifold { + var made := into; + var first: u32 = 0; + for i in 1..count { + if found[i].depth > found[first].depth { + first = i; + } + } + val p1 := found[first].point; + var second := first; + var best: f32 = -1; + for i in 0..count { + val d := (found[i].point - p1).length_squared; + if d > best { + best = d; + second = i; + } + } + val p2 := found[second].point; + var third := first; + var area: f32 = 0; + for i in 0..count { + val a := (p2 - p1).cross(found[i].point - p1).dot(n); + if math::abs(a) > math::abs(area) { + area = a; + third = i; + } + } + # Counterclockwise about the normal. + if area < 0 { + val swapped := second; + second = third; + third = swapped; + } + val q1 := found[first].point; + val q2 := found[second].point; + val q3 := found[third].point; + var fourth := first; + var added: f32 = 0; + for i in 0..count { + val q := found[i].point; + val a1 := (q1 - q).cross(q2 - q).dot(n); + val a2 := (q2 - q).cross(q3 - q).dot(n); + val a3 := (q3 - q).cross(q1 - q).dot(n); + val least := math::min(a1, math::min(a2, a3)); + if least < added { + added = least; + fourth = i; + } + } + made.points[0] = found[first]; + made.points[1] = found[second]; + made.points[2] = found[third]; + made.count = 3; + if fourth != first { + made.points[3] = found[fourth]; + made.count = 4; + } + return made; +} diff --git a/physics3d/contacts.sakura b/physics3d/contacts.sakura new file mode 100644 index 0000000..7778cf6 --- /dev/null +++ b/physics3d/contacts.sakura @@ -0,0 +1,499 @@ +#! Contains how a space finds which colliders are near one another, by the +#! boxes of its tree, and where those meet, as contacts kept from one step to +#! the next, so each begins with the impulses that held its bodies apart last. +#! Two shapes have one contact; a shape and a triangle mesh one for each +#! triangle they meet, named by the triangle, so it's kept as they slide. + +import std::containers; +import std::math; +import malunal::geometry; +import malunal::linear; +module malunal::physics3d; + +#! Two colliders that began or stopped touching in a step: sensors among +#! them, which touch where they overlap. +pub struct contact_event { + pub var a: collider_id; + pub var b: collider_id; + #! Whether they began touching, or stopped. + pub var began: bool; + #! Whether either is a sensor. + pub var sensor: bool; +} + +# Two colliders whose grown boxes meet, the first's index the lesser, and +# their contacts, a list of them: none of sensors, which only note whether +# they overlap. +struct pair_record { + var a: u32; + var b: u32; + var contacts: u32 = 0xFFFFFFFF; + var touching: bool; + var sensor: bool; + var mesh: bool; + var alive: bool; +} + +# Where two colliders meet, or a shape and one triangle of a mesh: the +# manifold, and the impulses that held them apart at each of its points last +# step, along the normal and the two tangents. +struct contact_record { + var pair: u32; + var child: u32; # The triangle, of a mesh's. + var next: u32 = 0xFFFFFFFF; + var body_a: u32; + var body_b: u32; + var manifold: manifold; + var normal_impulse: f32[4]; + var tangent_impulse: vec3[4]; # Along the first tangent, then the second. + var friction: f32; + var restitution: f32; + var touching: bool; + var seen: bool; + var alive: bool; +} + +# A triangle a shape met, and how. +struct met_triangle { + var triangle: u32; + var manifold: manifold; +} + +# A manifold's points and another's of the same normal, as four of them that +# hold the most of the area they hold. +def merge_into(into: &mut manifold, other: &manifold): void { + var found: contact[64]; + var count: u32 = 0; + for i in 0..into.count { + found[count] = into.points[i]; + count++; + } + for i in 0..other.count { + found[count] = other.points[i]; + count++; + } + if count <= max_contacts { + for i in 0..count { + into.points[i] = found[i]; + } + into.count = count; + return; + } + val kept := reduced(&found, count, into.normal, manifold{ normal = into.normal }); + into.points = kept.points; + into.count = kept.count; +} + +def pair_key(a: u32, b: u32): u64 { + val low := math::min(a, b) as u64; + val high := math::max(a, b) as u64; + return (low << 32) | high; +} + +# Whether two colliders may meet: of two bodies, one of them dynamic, or one +# a sensor and the other not static, on layers each other's masks hold, not +# both meshes, and not of bodies a joint keeps apart. +def space::may_meet(&this, a: u32, b: u32): bool { + val ca := &this.colliders[a as u64]; + val cb := &this.colliders[b as u64]; + return false if ca.body == cb.body || (ca.is_mesh() && cb.is_mesh()); + if !this.bodies[ca.body as u64].is_dynamic() && !this.bodies[cb.body as u64].is_dynamic() { + # A sensor meets what moves into it, kinematic as well as dynamic, but two + # standing still never meet. + return false if !ca.made.sensor && !cb.made.sensor; + return false if this.bodies[ca.body as u64].kind == body_kind::static && this.bodies[cb.body as u64].kind == body_kind::static; + } + return false if (ca.made.layers & cb.made.mask) == 0 || (cb.made.layers & ca.made.mask) == 0; + return !this.joined_apart(ca.body, cb.body); +} + +# Pairs each collider whose leaf moved with those its grown box newly meets. +def space::find_pairs(&mut this): void { + return if this.moved.length == 0; + var near := move(this.near); + for m in 0..this.moved.length { + val c := this.moved[m]; + continue if !this.colliders[c as u64].alive; + near.clear(); + this.tree.query(this.tree.box_of(this.colliders[c as u64].leaf), def(leaf: u32, data: u64): bool { + val other := data as u32; + if other != c && !(this.colliders[data].moved && other < c) { + near.append(other); + } + return true; + }); + for k in 0..near.length { + val other := near[k]; + val key := pair_key(c, other); + if this.may_meet(c, other) && !this.pair_keys.contains(&key) { + this.make_pair(math::min(c, other), math::max(c, other)); + } + } + } + for m in 0..this.moved.length { + this.colliders[this.moved[m] as u64].moved = false; + } + this.moved.clear(); + this.near = move(near); +} + +def space::make_pair(&mut this, a: u32, b: u32): void { + var p: u32 = 0; + if this.free_pairs.length > 0 { + p = this.free_pairs[this.free_pairs.length - 1]; + this.free_pairs.truncate(); + } else { + p = this.pairs.length as u32; + this.pairs.append(pair_record{}); + } + val sensor := this.colliders[a as u64].made.sensor || this.colliders[b as u64].made.sensor; + val mesh := this.colliders[a as u64].is_mesh() || this.colliders[b as u64].is_mesh(); + this.pairs[p as u64] = pair_record{ a = a, b = b, sensor = sensor, mesh = mesh, alive = true }; + this.pair_keys.set(pair_key(a, b), p); + if !sensor && !mesh { + this.pairs[p as u64].contacts = this.make_contact(p, 0); + } +} + +# A new contact of a pair, put first of its list. +def space::make_contact(&mut this, p: u32, child: u32): u32 { + var k: u32 = 0; + if this.free_contacts.length > 0 { + k = this.free_contacts[this.free_contacts.length - 1]; + this.free_contacts.truncate(); + } else { + k = this.contacts.length as u32; + this.contacts.append(contact_record{}); + } + val a := this.pairs[p as u64].a; + val b := this.pairs[p as u64].b; + val ma := &this.colliders[a as u64].made; + val mb := &this.colliders[b as u64].made; + this.contacts[k as u64] = contact_record{ + pair = p, child = child, next = this.pairs[p as u64].contacts, + body_a = this.colliders[a as u64].body, body_b = this.colliders[b as u64].body, + friction = math::sqrt(ma.friction * mb.friction), restitution = math::max(ma.restitution, mb.restitution), alive = true, + }; + return k; +} + +def space::free_contact(&mut this, k: u32): void { + this.contacts[k as u64].alive = false; + this.free_contacts.append(k); +} + +# Frees a pair and its contacts, noting it stopped where it touched, and +# waking its bodies then where `wake` is given. +def space::drop_pair(&mut this, p: u32, wake: bool): void { + val pair := this.pairs[p as u64]; + if pair.touching { + this.note(p, false); + if wake { + this.wake_body(this.colliders[pair.a as u64].body); + this.wake_body(this.colliders[pair.b as u64].body); + } + } + var k := pair.contacts; + while k != none { + val next := this.contacts[k as u64].next; + this.free_contact(k); + k = next; + } + this.pair_keys.remove(&pair_key(pair.a, pair.b)); + this.pairs[p as u64].alive = false; + this.free_pairs.append(p); +} + +def space::note(&mut this, p: u32, began: bool): void { + val a := this.pairs[p as u64].a; + val b := this.pairs[p as u64].b; + this.noted.append(contact_event{ + a = collider_id{ index = a, generation = this.colliders[a as u64].generation }, + b = collider_id{ index = b, generation = this.colliders[b as u64].generation }, + began = began, sensor = this.pairs[p as u64].sensor, + }); +} + +# Whether a body moves this step: dynamic or kinematic, and awake. +def space::moves(&this, b: u32): bool { + val body := &this.bodies[b as u64]; + return body.kind != body_kind::static && body.awake; +} + +# Where a pair's shapes meet: as the crew found it, where the step is solved on +# several threads, else found now. +def space::pair_manifold(&this, p: u32): manifold { + return this.found[p as u64] if this.threads > 1; + return this.manifold_of(this.pairs[p as u64].a, this.pairs[p as u64].b, this.speculative); +} + +# Finds where each pair of two shapes meets, on the crew, a block of pairs to +# each thread, as none needs another's: what it finds is put to use one pair at +# a time after, so a step gives the same on any number of threads. +def space::find_manifolds(&mut this): void { + this.found.clear(); + this.found.resize(this.pairs.length, manifold{}); + var job := pairs_job{ space = address(this) }; + val block := math::max(this.pairs.length / (this.threads as u64 * 8), 16u); + this.crew.run(run_pairs, address(&mut job) as *mut u8, this.pairs.length, block); +} + +struct pairs_job { + var space: *mut space; +} + +def run_pairs(context: *mut u8, begin: u64, end: u64): void { + val job := &through(context as *mut pairs_job); + val s := &mut through(job.space); + for p in begin..end { + val pair := &s.pairs[p]; + continue if !pair.alive || pair.sensor || pair.mesh; + val ca := &s.colliders[pair.a as u64]; + val cb := &s.colliders[pair.b as u64]; + continue if !s.moves(ca.body) && !s.moves(cb.body); + continue if !s.tree.box_of(ca.leaf).overlaps(s.tree.box_of(cb.leaf)); + s.found[p] = s.manifold_of(pair.a, pair.b, s.speculative); + } +} + +# Finds where each pair of a moving body meets, dropping those whose grown +# boxes no longer meet. +def space::update_contacts(&mut this): void { + if this.threads > 1 { + this.find_manifolds(); + } + for p in 0..this.pairs.length { + continue if !this.pairs[p].alive; + val a := this.pairs[p].a; + val b := this.pairs[p].b; + val ba := this.colliders[a as u64].body; + val bb := this.colliders[b as u64].body; + continue if !this.moves(ba) && !this.moves(bb); + if !this.tree.box_of(this.colliders[a as u64].leaf).overlaps(this.tree.box_of(this.colliders[b as u64].leaf)) { + this.drop_pair(p as u32, false); + continue; + } + var touching := false; + if this.pairs[p].sensor { + touching = this.sensed(a, b); + } else if this.pairs[p].mesh { + touching = this.update_mesh_contacts(p as u32); + } else { + touching = this.update_contact(this.pairs[p].contacts, this.pair_manifold(p as u32)); + } + if touching != this.pairs[p].touching { + this.pairs[p].touching = touching; + this.note(p as u32, touching); + if touching && !this.pairs[p].sensor { + this.note_hit(p as u32); + } + } + if touching { + this.wake_if_pushed(ba, bb); + this.wake_if_pushed(bb, ba); + } + } +} + +# Wakes a sleeping dynamic body where what touches it is awake and moves it: a +# dynamic body, or a kinematic one moving. +def space::wake_if_pushed(&mut this, b: u32, by: u32): void { + return if this.bodies[b as u64].awake || this.bodies[b as u64].kind != body_kind::dynamic; + val other := &this.bodies[by as u64]; + if other.awake && (other.kind == body_kind::dynamic || other.velocity.length_squared > 0 || other.spin.length_squared > 0) { + this.wake_body(b); + } +} + +# Where two colliders' shapes meet, within a margin. +def space::manifold_of(&this, a: u32, b: u32, margin: f32): manifold { + val ca := &this.colliders[a as u64]; + val cb := &this.colliders[b as u64]; + if collide(&ca.made.shape, this.bodies[ca.body as u64].at, &cb.made.shape, this.bodies[cb.body as u64].at, margin) is some(m) { + return m; + } + return manifold{}; +} + +# Whether a sensor's pair overlaps: a shape and a shape, or a shape and a +# mesh. +def space::sensed(&this, a: u32, b: u32): bool { + val ca := &this.colliders[a as u64]; + val cb := &this.colliders[b as u64]; + val at_a := this.bodies[ca.body as u64].at; + val at_b := this.bodies[cb.body as u64].at; + return this.meshes[ca.mesh as u64].overlaps(at_a, &cb.made.shape, at_b) if ca.is_mesh(); + return this.meshes[cb.mesh as u64].overlaps(at_b, &ca.made.shape, at_a) if cb.is_mesh(); + return overlaps(&ca.made.shape, at_a, &cb.made.shape, at_b); +} + +# Gives a contact a manifold, each point beginning with the impulses of last +# step's point of the same features. +# @returns Whether it touches, within the speculative margin. +def space::update_contact(&mut this, k: u32, found: manifold): bool { + val c := &mut this.contacts[k as u64]; + var normal: f32[4] = [0, 0, 0, 0]; + var tangent: vec3[4]; + for i in 0..found.count { + for j in 0..c.manifold.count { + if found.points[i].id == c.manifold.points[j].id { + normal[i] = c.normal_impulse[j]; + tangent[i] = c.tangent_impulse[j]; + } + } + } + c.manifold = found; + c.normal_impulse = normal; + c.tangent_impulse = tangent; + c.touching = found.count > 0; + c.seen = true; + return c.touching; +} + +# Finds the triangles a shape meets of a mesh, a contact for each, keeping +# those it met last step and dropping those it no longer meets. +# @returns Whether any touches. +def space::update_mesh_contacts(&mut this, p: u32): bool { + val a := this.pairs[p as u64].a; + val b := this.pairs[p as u64].b; + # The mesh as the first, its normals from each triangle toward the shape, + # turned back where the shape is the pair's first. + val mesh_first := this.colliders[a as u64].is_mesh(); + val m := mesh_first ? a : b; + val s := mesh_first ? b : a; + var met := move(this.met); + met.clear(); + val held := &this.colliders[m as u64]; + val shaped := &this.colliders[s as u64]; + this.meshes[held.mesh as u64].collide(this.bodies[held.body as u64].at, &shaped.made.shape, this.bodies[shaped.body as u64].at, this.speculative, def(t: u32, found: manifold): bool { + # Triangles facing one way are met as one, their points together, as Jolt + # meets them, so a box resting across a seam is pushed as on one face, + # not one triangle's after the other's, which would edge it aside. Each + # point's id is mixed with its triangle, so points of two are told apart. + var made := mesh_first ? found : found.flipped(); + val mixed := ((t as u64 * 0x9E3779B1) & 0xFFFFFFFF) as u32; + for i in 0..made.count { + made.points[i].id = made.points[i].id ^ mixed; + } + for k in 0..met.length { + if met[k].manifold.normal.dot(made.normal) > 0.999 { + merge_into(&mut met[k].manifold, &made); + return true; + } + } + met.append(met_triangle{ triangle = t, manifold = made }); + return true; + }); + var k := this.pairs[p as u64].contacts; + while k != none { + this.contacts[k as u64].seen = false; + k = this.contacts[k as u64].next; + } + var touching := false; + for i in 0..met.length { + var found := this.pairs[p as u64].contacts; + while found != none && this.contacts[found as u64].child != met[i].triangle { + found = this.contacts[found as u64].next; + } + if found == none { + found = this.make_contact(p, met[i].triangle); + this.pairs[p as u64].contacts = found; + } + if this.update_contact(found, met[i].manifold) { + touching = true; + } + } + this.met = move(met); + # Those not met this step are dropped. + var previous: u32 = none; + k = this.pairs[p as u64].contacts; + while k != none { + val next := this.contacts[k as u64].next; + if !this.contacts[k as u64].seen { + if previous == none { + this.pairs[p as u64].contacts = next; + } else { + this.contacts[previous as u64].next = next; + } + this.free_contact(k); + } else { + previous = k; + } + k = next; + } + return touching; +} + +#! Two colliders that began touching in a step faster than the space's +#! `hit_speed`, as something landing does: which, where, the normal from the +#! first toward the second, and how fast they met along it, as a sound of it +#! might be loud. +pub struct hit_event { + pub var a: collider_id; + pub var b: collider_id; + pub var point: vec3; + pub var normal: vec3; + pub var speed: f32; +} + +#! The hits of the last step. +pub def space::hits(&this): span { + return this.struck.span; +} + +# How fast a body's place moves, of a place of space. +def space::speed_at(&this, index: u32, at: vec3): vec3 { + val b := &this.bodies[index as u64]; + val r := at - b.center; + return b.velocity + b.spin.cross(r); +} + +# Notes how hard a pair that began touching met, where it met faster than the +# hit speed: at its first point, as the step began. +def space::note_hit(&mut this, p: u32): void { + var k := this.pairs[p as u64].contacts; + while k != none && this.contacts[k as u64].manifold.count == 0 { + k = this.contacts[k as u64].next; + } + return if k == none; + val c := &this.contacts[k as u64]; + val point := c.manifold.points[0].point; + val n := c.manifold.normal; + val speed := -n.dot(this.speed_at(c.body_b, point) - this.speed_at(c.body_a, point)); + return if speed < this.hit_speed; + val a := this.pairs[p as u64].a; + val b := this.pairs[p as u64].b; + this.struck.append(hit_event{ + a = collider_id{ index = a, generation = this.colliders[a as u64].generation }, + b = collider_id{ index = b, generation = this.colliders[b as u64].generation }, + point = point, normal = n, speed = speed, + }); +} + +#! Visits each pair of colliders touching as the last step left them, a +#! sensor's among them where it overlaps what it meets, as `visit(a, b, +#! sensor)`, until it gives false: what began and stopped touching since a +#! step before, by what it visited then, however colliders were taken away +#! and attached between. +pub def space::each_touching(&this, visit: F): void where F: invokable { + for p in 0..this.pairs.length { + val pair := &this.pairs[p]; + continue if !pair.alive || !pair.touching; + return if !visit(this.named(pair.a), this.named(pair.b), pair.sensor); + } +} +#! Visits each point of each contact touching, as `visit(a, b, point, normal, +#! depth)`, of its two colliders, its normal from the first toward the +#! second, until it gives false, as gizmos draw them. +pub def space::each_contact(&this, visit: F): void where F: invokable { + for k in 0..this.contacts.length { + val c := &this.contacts[k]; + continue if !c.alive || !c.touching; + val pair := &this.pairs[c.pair as u64]; + val a := collider_id{ index = pair.a, generation = this.colliders[pair.a as u64].generation }; + val b := collider_id{ index = pair.b, generation = this.colliders[pair.b as u64].generation }; + for i in 0..c.manifold.count { + return if !visit(a, b, c.manifold.points[i].point, c.manifold.normal, c.manifold.points[i].depth); + } + } +} \ No newline at end of file diff --git a/physics3d/continuous.sakura b/physics3d/continuous.sakura new file mode 100644 index 0000000..8c31600 --- /dev/null +++ b/physics3d/continuous.sakura @@ -0,0 +1,123 @@ +#! Contains continuous collision, as in a plane: a dynamic body that moved +#! further in a step than half the least its shapes reach is swept, from where +#! it began the step to where it ended it, against what stands still, a mesh's +#! triangles and a heightfield's among it, and put back where it first comes +#! within the slop of what it met, its velocity kept, so the next step's +#! contacts stop it there. A bullet is swept against moving bodies too, where +#! they ended the step. + +import std::containers; +import std::math; +import malunal::geometry; +import malunal::linear; +module malunal::physics3d; + +# A body moving fast enough this step to pass through something thin, and how +# it moved. +struct fast_body { + var body: u32; + var moved: sweep; +} + +# Notes a body that moved fast enough to be swept, as the step ends. +def space::note_fast(&mut this, b: u32, moved: sweep): void { + val body := &this.bodies[b as u64]; + return if !this.continuous || body.kind != body_kind::dynamic || body.least <= 0; + val travel := (moved.c2 - moved.c1).length + moved.turning() * body.extent; + if travel > 0.5 * body.least { + this.fast.append(fast_body{ body = b, moved = moved }); + } +} + +# Sweeps the fast bodies, bullets last, so they meet the rest where they end +# up, and places their colliders. +def space::sweep_fast(&mut this): void { + var fast := move(this.fast); + for pass in 0..2u { + for i in 0..fast.length { + val bullet := this.bodies[fast[i].body as u64].bullet; + continue if bullet != (pass == 1); + this.sweep_body(&fast[i]); + this.place_colliders(fast[i].body); + } + } + fast.clear(); + this.fast = move(fast); +} + +# Puts a fast body back where it first meets what it may pass through. +def space::sweep_body(&mut this, f: &fast_body): void { + val b := f.body; + val bullet := this.bodies[b as u64].bullet; + val target := this.slop; + val tolerance := 0.25 * this.slop; + var first: f32 = 1; + var c := this.bodies[b as u64].colliders; + while c != none { + val own := &this.colliders[c as u64]; + if !own.made.sensor && !own.is_mesh() { + val box := own.made.shape.bounds(f.moved.at(0)).merged(own.made.shape.bounds(f.moved.at(1))); + this.tree.query(box, def(leaf: u32, data: u64): bool { + val other := &this.colliders[data]; + return true if other.body == b || other.made.sensor; + return true if (other.made.layers & own.made.mask) == 0 || (own.made.layers & other.made.mask) == 0; + val held := &this.bodies[other.body as u64]; + return true if held.kind != body_kind::static && (!bullet || held.bullet); + return true if this.joined_apart(b, other.body); + val still := sweep::still(held.at); + if other.is_mesh() { + val surface := &this.meshes[other.mesh as u64]; + val start := f.moved.at(0); + val end := f.moved.at(1); + surface.triangles_in(local_box(box, held.at), def(t: u32): bool { + val corners := surface.triangle(t); + # Only a triangle whose plane it reaches by the step's end, from + # in front of it, may it pass through. + val n := held.at.rotate(surface.normal(t)); + val offset := n.dot(held.at.apply(corners[0])); + return true if -reach_along(&own.made.shape, end, -n) - offset > target; + return true if reach_along(&own.made.shape, start, n) - offset < 0; + val face := shape::of_hull(hull::triangle(corners[0], corners[1], corners[2])); + val at := impact_of(&face, &still, &own.made.shape, &f.moved, target, tolerance); + if at > 0 && at < first { + first = at; + } + return true; + }); + return true; + } + val at := impact_of(&other.made.shape, &still, &own.made.shape, &f.moved, target, tolerance); + if at > 0 && at < first { + first = at; + } + return true; + }); + } + c = this.colliders[c as u64].next; + } + return if first >= 1; + val at := f.moved.at(first); + this.bodies[b as u64].at = at; + this.bodies[b as u64].center = at.apply(this.bodies[b as u64].local_center); +} + +# When a fast shape first meets what stands still: where they touch as the +# step begins, when a small sphere about the fast shape's middle first meets +# it, so its middle at least never passes through, as Box2D finds it. +def impact_of(still_shape: &shape, still: &sweep, fast: &shape, moved: &sweep, target: f32, tolerance: f32): f32 { + val t := time_of_impact(still_shape, still, fast, moved, target, tolerance); + return t if t > 0; + val core := shape::sphere(0.25 * fast.least_reach(), fast.middle()); + return time_of_impact(still_shape, still, &core, moved, target, tolerance); +} + +# A box of space as one of a pose's own places, holding it however it's +# turned. +def local_box(box: bounds, at: pose): bounds { + var made := bounds::blank; + for i in 0..8u { + val corner := vec3{ (i & 1) != 0 ? box.max.x : box.min.x, (i & 2) != 0 ? box.max.y : box.min.y, (i & 4) != 0 ? box.max.z : box.min.z }; + made = made.including(at.unapply(corner)); + } + return made; +} diff --git a/physics3d/crew.sakura b/physics3d/crew.sakura new file mode 100644 index 0000000..ea6a5f5 --- /dev/null +++ b/physics3d/crew.sakura @@ -0,0 +1,140 @@ +#! Contains `crew`: the threads a space solves a step's colors on, besides +#! its caller's, started as a step first asks for more than one and kept until +#! the space closes. Each job is a number of things, taken a block at a time by +#! whichever thread is free, the caller among them, which returns once all are +#! done. Between jobs, as a step's come one after another, the threads spin a +#! little before sleeping, so a job begins in a microsecond rather than the +#! tens a sleeping thread takes to wake, as Box2D's workers spin. They spin by +#! reading what they wait on: `system::pause` is the system's wait for a signal, +#! not the processor's hint that a thread spins. + +import system; +import std::containers; +import std::thread; +module malunal::physics3d; + +# What the threads are given to do: a function for each range of things. +struct crew_job { + var run: def(*mut u8, u64, u64): void; + var context: *mut u8; + var count: u64; + var block: u64; +} + +# What the threads share, on the heap, so it stays where it is. +struct crew_state { + var job: crew_job; + var next: atomic; # The job's round, high, and the next thing to take, low. + var done: atomic; # How many things are done. + var round: atomic; # Counts jobs, and the threads wait on it. + var sleeping: atomic; # How many threads sleep rather than spin. + var stopping: atomic; +} + +# How many times a thread spins waiting for a job before it sleeps. +const spins: u32 = 200000; + +# The threads a space solves on, besides its caller's. +struct crew : owning { + var shared: *mut crew_state; + var threads: vector>; +} + +# Starts threads, so there are as many as asked for in all, the caller's among +# them, where there aren't. +def crew::start(&mut this, count: u32): void { + if this.shared != null && this.threads.length + 1 != count as u64 { + this.close(); + } + return if this.shared != null || count <= 1; + this.shared = raw_allocate_zeroed(size_of::()) as *mut crew_state; + for _ in 1..count { + var started := thread::spawn_with(work, this.shared) else (_) { break; }; + this.threads.append(move(started)); + } +} + +# Runs a function over ranges of a job's things, a block at a time, on this +# thread and the crew's, and returns once all are done. +def crew::run(&mut this, run: def(*mut u8, u64, u64): void, context: *mut u8, count: u64, block: u64): void { + return if count == 0; + if this.shared == null || count <= block { + run(context, 0, count); + return; + } + val s := &mut through(this.shared); + # The next round's things first, so a thread late from the last takes none + # of this job's by the last's function. + val round := s.round.load(order::relaxed) + 1; + s.next.store((round as u64) << 32, order::release); + s.job = crew_job{ run = run, context = context, count = count, block = block }; + s.done.store(0, order::relaxed); + s.round.store(round, order::release); + if s.sleeping.load(order::acquire) > 0 { + _ = system::futex_wake(word_of(&mut s.round), 0x7FFFFFFF); + } + drain(s, round); + while s.done.load(order::acquire) < count { + } +} + +pub def crew::close(&mut this): void { + if this.shared != null { + val s := &mut through(this.shared); + s.stopping.store(1, order::release); + _ = s.round.fetch_add(1, order::release); + _ = system::futex_wake(word_of(&mut s.round), 0x7FFFFFFF); + this.threads.close(); + raw_release(this.shared as *mut u8); + this.shared = null; + } + this.threads.close(); +} + +# What each thread does: waits for a job, spinning then sleeping, and takes +# its things until none are left. +def work(shared: *mut crew_state): void { + val s := &mut through(shared); + var seen: u32 = 0; + while true { + var round := s.round.load(order::acquire); + var spun: u32 = 0; + while round == seen { + if spun < spins { + spun++; + } else { + _ = s.sleeping.fetch_add(1, order::acq_rel); + if s.round.load(order::acquire) == seen { + _ = system::futex_wait(word_of(&mut s.round), seen, -1); + } + _ = s.sleeping.fetch_sub(1, order::acq_rel); + } + round = s.round.load(order::acquire); + } + seen = round; + return if s.stopping.load(order::acquire) != 0; + drain(s, round); + } +} + +# Takes blocks of a round's job, running its function over each, until none +# are left, or the round has passed. +def drain(s: &mut crew_state, round: u32): void { + val job := s.job; + while true { + val held := s.next.load(order::acquire); + return if (held >> 32) as u32 != round; + val at := held & 0xFFFFFFFF; + return if at >= job.count; + val claimed := s.next.compare_exchange_weak(held, held + job.block, order::acq_rel, order::acquire); + continue if claimed is error(_); + val end := at + job.block < job.count ? at + job.block : job.count; + job.run(job.context, at, end); + _ = s.done.fetch_add(end - at, order::acq_rel); + } +} + +# The word of an atomic, which the system's futexes wait on. +def word_of(of: &mut atomic): *mut u32 { + return (address(of) as *mut atomic) as *mut u32; +} diff --git a/physics3d/distance.sakura b/physics3d/distance.sakura new file mode 100644 index 0000000..ae05a6a --- /dev/null +++ b/physics3d/distance.sakura @@ -0,0 +1,451 @@ +#! Contains how far apart two shapes are, their nearest places found as +#! Gilbert, Johnson, and Keerthi's GJK finds them; a shape cast along a motion, +#! to where it first meets another; and the time of impact of two shapes each +#! swept through a step, moving and turning, as continuous collision asks. +#! +#! GJK finds the place of the shapes' difference, every place of the second +#! less every place of the first, nearest the origin, by a tetrahedron of its +#! corners at most, each step adding the corner furthest toward the origin and +#! keeping only the corner, edge, or face the nearest place lies on, as +#! Ericson's Real-Time Collision Detection finds it. It works each shape's +#! core, a sphere's middle, a capsule's segment, or a hull, then takes the radii +#! off, so a sphere's nearest place is as exact as a box's. +#! +#! A cast, and a time of impact, advance conservatively, as Mirtich's do: each +#! moves the shapes as far as the gap between them, over how fast they can +#! close it, says they can't yet meet, so neither ever passes through what it +#! meets. + +import std::math; +import malunal::linear; +module malunal::physics3d; + +#! How far apart two shapes are, and the places of each nearest the other. +pub struct gap { + #! The places of the first's surface and the second's nearest one another: + #! one place, midway, where they meet. + pub var on_a: vec3; + pub var on_b: vec3; + #! The direction from the first toward the second, of length 1, or none + #! where they meet. + pub var normal: vec3; + #! How far apart their surfaces are: 0 where they meet. + pub var distance: f32; +} + +#! Where a shape cast along a motion first met another: how far along the +#! motion, as a fraction of it, the place of the other's surface it met, and +#! which way that surface faces, toward the shape cast. +pub struct cast_hit { + pub var fraction: f32; + pub var point: vec3; + pub var normal: vec3; +} + +# A corner of the shapes' difference, of a point of each, and its weight in +# the nearest place. +struct corner { + var on_a: vec3; + var on_b: vec3; + var w: vec3; + var weight: f32; + var ia: u32; + var ib: u32; +} + +# As many as four corners, the nearest place lying among them. +struct simplex { + var corners: corner[4]; + var count: u32; +} + +# A point of a shape's core: a sphere's middle, a capsule's end, or a hull's +# corner. +def core_point(s: &shape, i: u32): vec3 { + return s.as_hull().point(i) if s.kind == shape_kind::hull; + return i == 0 ? s.a : s.b; +} + +# The point of a shape's core furthest along a direction of space, where a +# pose places it. +def support_of(s: &shape, at: &pose, direction: vec3): u32 { + val d := at.unrotate(direction); + return s.as_hull().support(d) if s.kind == shape_kind::hull; + return 1 if s.kind == shape_kind::capsule && (s.b - s.a).dot(d) > 0; + return 0; +} + +def corner_of(a: &shape, at_a: &pose, ia: u32, b: &shape, at_b: &pose, ib: u32): corner { + val pa := at_a.apply(core_point(a, ia)); + val pb := at_b.apply(core_point(b, ib)); + return corner{ on_a = pa, on_b = pb, w = pb - pa, weight = 1, ia = ia, ib = ib }; +} + +# Keeps one corner of the simplex. +def keep_one(x: &mut simplex, i: u32): void { + val kept := x.corners[i]; + x.corners[0] = kept; + x.corners[0].weight = 1; + x.count = 1; +} + +# Keeps two corners of the simplex, weighted so. +def keep_two(x: &mut simplex, i: u32, j: u32, wi: f32, wj: f32): void { + val first := x.corners[i]; + val second := x.corners[j]; + x.corners[0] = first; + x.corners[0].weight = wi; + x.corners[1] = second; + x.corners[1].weight = wj; + x.count = 2; +} + +# The nearest place of a segment of the difference to the origin. +def solve2(x: &mut simplex): void { + val a := x.corners[0].w; + val ab := x.corners[1].w - a; + val along := -a.dot(ab); + if along <= 0 { + keep_one(x, 0); + return; + } + val length := ab.dot(ab); + if along >= length || length <= tiny * tiny { + keep_one(x, 1); + return; + } + val t := along / length; + keep_two(x, 0, 1, 1 - t, t); +} + +# The nearest place of a triangle of the difference to the origin, by which of +# its corners, edges, or face it's on, as Ericson finds it. +def solve3(x: &mut simplex): void { + val a := x.corners[0].w; + val b := x.corners[1].w; + val c := x.corners[2].w; + val ab := b - a; + val ac := c - a; + val d1 := -ab.dot(a); + val d2 := -ac.dot(a); + if d1 <= 0 && d2 <= 0 { + keep_one(x, 0); + return; + } + val d3 := -ab.dot(b); + val d4 := -ac.dot(b); + if d3 >= 0 && d4 <= d3 { + keep_one(x, 1); + return; + } + val vc := d1 * d4 - d3 * d2; + if vc <= 0 && d1 >= 0 && d3 <= 0 { + val v := d1 / (d1 - d3); + keep_two(x, 0, 1, 1 - v, v); + return; + } + val d5 := -ab.dot(c); + val d6 := -ac.dot(c); + if d6 >= 0 && d5 <= d6 { + keep_one(x, 2); + return; + } + val vb := d5 * d2 - d1 * d6; + if vb <= 0 && d2 >= 0 && d6 <= 0 { + val w := d2 / (d2 - d6); + keep_two(x, 0, 2, 1 - w, w); + return; + } + val va := d3 * d6 - d5 * d4; + if va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0 { + val w := (d4 - d3) / ((d4 - d3) + (d5 - d6)); + keep_two(x, 1, 2, 1 - w, w); + return; + } + # A triangle of no area, its corners in a line: its nearest edge. + if ab.cross(ac).length_squared <= 1e-12 * ab.length_squared * ac.length_squared { + nearest_edge(x); + return; + } + val inv := 1 / (va + vb + vc); + val v := vb * inv; + val w := vc * inv; + x.corners[0].weight = 1 - v - w; + x.corners[1].weight = v; + x.corners[2].weight = w; + x.count = 3; +} + +# Keeps the edge of three corners nearest the origin, as `solve2` keeps it. +def nearest_edge(x: &mut simplex): void { + val pairs: u32[6] = [0, 1, 0, 2, 1, 2]; + var best := 1e30f; + var kept := simplex{}; + for k in 0..3u { + var edge := simplex{ count = 2 }; + edge.corners[0] = x.corners[pairs[k * 2]]; + edge.corners[1] = x.corners[pairs[k * 2 + 1]]; + solve2(&mut edge); + var v := vec3::zero; + for q in 0..edge.count { + v = v + edge.corners[q].w * edge.corners[q].weight; + } + if v.length_squared < best { + best = v.length_squared; + kept = edge; + } + } + x.corners = kept.corners; + x.count = kept.count; +} + +# Six times the signed volume of a tetrahedron. +def volume(a: vec3, b: vec3, c: vec3, d: vec3): f32 { + return (b - a).dot((c - a).cross(d - a)); +} + +# The nearest place of a tetrahedron of the difference to the origin: within +# it, or on the nearest of the faces it's outside of. +def solve4(x: &mut simplex): void { + val w: vec3[4] = [x.corners[0].w, x.corners[1].w, x.corners[2].w, x.corners[3].w]; + # Each face, and the corner across from it. + val faces: u32[16] = [0, 1, 2, 3, 0, 2, 3, 1, 0, 3, 1, 2, 1, 3, 2, 0]; + var best := 1e30f; + var nearest := simplex{}; + var outside := false; + for f in 0..4u { + val i := faces[f * 4]; + val j := faces[f * 4 + 1]; + val k := faces[f * 4 + 2]; + val across := faces[f * 4 + 3]; + val n := (w[j] - w[i]).cross(w[k] - w[i]); + val origin_side := -n.dot(w[i]); + val other_side := n.dot(w[across] - w[i]); + # The origin's beyond this face where it's on the side away from the + # corner across from it, or the tetrahedron is flat, the corner across + # nearly in the face's plane, for as large as the face is. + val flat := math::abs(other_side) <= 1e-5 * n.length * (w[across] - w[i]).length; + if origin_side * other_side < 0 || flat { + outside = true; + var face := simplex{ count = 3 }; + face.corners[0] = x.corners[i]; + face.corners[1] = x.corners[j]; + face.corners[2] = x.corners[k]; + solve3(&mut face); + var v := vec3::zero; + for q in 0..face.count { + v = v + face.corners[q].w * face.corners[q].weight; + } + if v.length_squared < best { + best = v.length_squared; + nearest = face; + } + } + } + if outside { + x.corners = nearest.corners; + x.count = nearest.count; + return; + } + val whole := volume(w[0], w[1], w[2], w[3]); + val o := vec3::zero; + x.corners[0].weight = volume(o, w[1], w[2], w[3]) / whole; + x.corners[1].weight = volume(w[0], o, w[2], w[3]) / whole; + x.corners[2].weight = volume(w[0], w[1], o, w[3]) / whole; + x.corners[3].weight = volume(w[0], w[1], w[2], o) / whole; + x.count = 4; +} + +# Keeps the corners of a simplex the nearest place lies among, weighted. +def solve(x: &mut simplex): void { + if x.count == 2 { + solve2(x); + } else if x.count == 3 { + solve3(x); + } else if x.count == 4 { + solve4(x); + } +} + +#! How far apart two shapes are, each where its pose places it, and the places +#! of each nearest the other: none apart where they meet. +pub def gap_between(a: &shape, at_a: pose, b: &shape, at_b: pose): gap { + var x := simplex{ count = 1 }; + x.corners[0] = corner_of(a, &at_a, 0, b, &at_b, 0); + var last := 1e30f; + for iteration in 0..32u { + solve(&mut x); + + # Four corners hold the origin: the cores overlap. + if x.count == 4 { + break; + } + var v := vec3::zero; + for i in 0..x.count { + v = v + x.corners[i].w * x.corners[i].weight; + } + val squared := v.length_squared; + # Nearer no more, as rounding among large places may leave it, adding + # the same face's corners again: it's found. + if squared < tiny * tiny || squared >= last { + break; + } + last = squared; + val ia := support_of(a, &at_a, v); + val ib := support_of(b, &at_b, -v); + val next := corner_of(a, &at_a, ia, b, &at_b, ib); + # No corner further toward the origin than the nearest place: it's found. + if squared - v.dot(next.w) <= 1e-6 * squared { + break; + } + var again := false; + for i in 0..x.count { + if x.corners[i].ia == ia && x.corners[i].ib == ib { + again = true; + } + } + if again { + break; + } + x.corners[x.count] = next; + x.count++; + } + solve(&mut x); + var on_a := vec3::zero; + var on_b := vec3::zero; + for i in 0..x.count { + on_a = on_a + x.corners[i].on_a * x.corners[i].weight; + on_b = on_b + x.corners[i].on_b * x.corners[i].weight; + } + if x.count == 4 { + on_b = on_a; + } + val between := on_b - on_a; + val cores := between.length; + val reach := a.radius + b.radius; + if cores > reach && cores > tiny { + val normal := between * (1 / cores); + return gap{ on_a = on_a + normal * a.radius, on_b = on_b - normal * b.radius, normal = normal, distance = cores - reach }; + } + val normal := cores > tiny ? between * (1 / cores) : vec3::zero; + val middle := ((on_a + normal * a.radius) + (on_b - normal * b.radius)) * 0.5; + return gap{ on_a = middle, on_b = middle, normal = normal, distance = 0 }; +} + +#! Where a shape, `b`, cast along a motion of space from where its pose places +#! it, first meets another, `a`, which stays where its pose places it: within +#! `tolerance` of its surface, a little short of touching, so what's moved there +#! doesn't overlap. Nothing where it doesn't meet it within the motion; a +#! fraction of 0 where they meet as it begins, its normal back along the +#! motion. +pub def shape_cast(a: &shape, at_a: pose, b: &shape, at_b: pose, motion: vec3, tolerance: f32 = 0.0025): maybe { + val target := 0.5 * tolerance; + var t: f32 = 0; + var at := at_b; + for iteration in 0..30u { + val g := gap_between(a, at_a, b, at); + if g.distance <= tolerance { + val back := g.distance > 0 ? g.normal : -motion.normalized(); + return cast_hit{ fraction = t, point = g.on_a, normal = back }; + } + val approach := -motion.dot(g.normal); + return nothing{} if approach <= tiny; + t += (g.distance - target) / approach; + return nothing{} if t > 1; + at = pose{ at = at_b.at + motion * t, turn = at_b.turn }; + } + val g := gap_between(a, at_a, b, at); + return cast_hit{ fraction = t, point = g.on_a, normal = g.normal }; +} + +#! How a body moves through a step: its center of mass, of its own places, +#! where that center begins and ends the step, and how it's turned as it begins +#! and ends it, turning the shorter way between. +pub struct sweep { + pub var local_center: vec3; + pub var c1: vec3; + pub var c2: vec3; + pub var q1 := quat::identity; + pub var q2 := quat::identity; +} + +#! A sweep standing still where a pose places a body. +pub def sweep::still(at: pose, local_center: vec3 = vec3::zero): sweep { + val center := at.apply(local_center); + return sweep{ local_center = local_center, c1 = center, c2 = center, q1 = at.turn, q2 = at.turn }; +} + +#! Where it places its body a fraction of the way through the step. +pub def sweep::at(&this, t: f32): pose { + val turn := this.q1.slerp(this.q2, t); + val center := this.c1.lerp(this.c2, t); + return pose{ at = center - turn * this.local_center, turn = turn }; +} + +# How far it turns through the step, in radians. +def sweep::turning(&this): f32 { + val cosine := math::min(math::abs(this.q1.dot(this.q2)), 1f); + return 2 * math::acos(cosine); +} + +# How far a shape's surface reaches from a place of its own. +def reach_from(s: &shape, center: vec3): f32 { + if s.kind == shape_kind::hull { + var most: f32 = 0; + val h := s.as_hull(); + for i in 0..h.count { + most = math::max(most, (h.point(i) - center).length); + } + return most; + } + return math::max((s.a - center).length, (s.b - center).length) + s.radius; +} + +#! When, as a fraction of the step, two shapes each swept through it first come +#! within `target` of one another, to within `tolerance`, as their sweeps move +#! and turn them: 1 where they don't. Each moves no further than they can, as +#! fast as they close and turn, without meeting, so what's found is never past +#! where they meet. +pub def time_of_impact(a: &shape, sa: &sweep, b: &shape, sb: &sweep, target: f32, tolerance: f32): f32 { + val turn_a := sa.turning() * reach_from(a, sa.local_center); + val turn_b := sb.turning() * reach_from(b, sb.local_center); + val moved := (sb.c2 - sb.c1) - (sa.c2 - sa.c1); + var t: f32 = 0; + for iteration in 0..50u { + val g := gap_between(a, sa.at(t), b, sb.at(t)); + return t if g.distance <= target + tolerance; + val closing := -moved.dot(g.normal) + turn_a + turn_b; + return 1 if closing <= tiny; + t += (g.distance - target) / closing; + return 1 if t >= 1; + } + return t; +} + +# How far a shape reaches along a direction of space, where a pose places it. +def reach_along(s: &shape, at: pose, direction: vec3): f32 { + if s.kind == shape_kind::hull { + val h := s.as_hull(); + return direction.dot(at.apply(h.point(h.support(at.unrotate(direction))))); + } + return math::max(direction.dot(at.apply(s.a)), direction.dot(at.apply(s.b))) + s.radius; +} + +# The middle of a shape: a sphere's, a capsule's, or a hull's center. +def shape::middle(&this): vec3 { + return this.as_hull().center if this.kind == shape_kind::hull; + return (this.a + this.b) * 0.5; +} + +# How far a shape reaches at least from its middle: a sphere's or a capsule's +# radius, or the nearest of a hull's faces, as a body may move without passing +# through what's in its way. +def shape::least_reach(&this): f32 { + return this.radius if this.kind != shape_kind::hull; + val h := this.as_hull(); + var least := 1e30f; + for f in 0..h.faces { + least = math::min(least, h.offset(f) - h.normal(f).dot(h.center)); + } + return least; +} diff --git a/physics3d/free_joints.sakura b/physics3d/free_joints.sakura new file mode 100644 index 0000000..4f179d7 --- /dev/null +++ b/physics3d/free_joints.sakura @@ -0,0 +1,255 @@ +#! Contains how a step solves sliders, ball joints' limits, and six-way joints, +#! as Box2D's soft step solves the rest: each way a joint holds is a row of its +#! own, pushed toward holding it, softly where `use_bias` asks, a limit only as +#! far as closes it, as a speculative contact. +#! +#! A joint's turn is taken within its frame as a twist about its x axis and a +#! swing after it, as Jolt's swing-twist joints take it: a ball joint's swing is +#! held within its cone, and a six-way joint's swing about y and z each within +#! its own limits, as a pyramid. + +import std::math; +import malunal::linear; +module malunal::physics3d; + +# A joint's frame and levers as its bodies have moved and turned since the step +# began: its axes in space, from `a`'s anchor to `b`'s, and the turn of `b`'s +# frame within `a`'s, as a twist and a swing. +struct joint_frame { + var x: vec3; # Of `a`'s frame. + var y: vec3; + var z: vec3; + var twist_x: vec3; # `b`'s frame's x, which it twists about, + var swing_y: vec3; # and `a`'s y and z across it, which it swings about. + var swing_z: vec3; + var ra: vec3; + var rb: vec3; + var d: vec3; + var twist: f32; + var swung_y: f32; + var swung_z: f32; +} + +def frame_of(r: &joint_record, sa: &body_state, sb: &body_state): joint_frame { + val fa := ((sa.dq * r.qa).normalized() * r.made.frame_a).normalized(); + val fb := ((sb.dq * r.qb).normalized() * r.made.frame_b).normalized(); + val ra := sa.dq * r.ra; + val rb := sb.dq * r.rb; + val x := fa * vec3::right; + val y := fa * vec3::up; + val z := fa * vec3::back; + val bx := fb * vec3::right; + var made := joint_frame{ + x = x, y = y, z = z, twist_x = bx, + swing_y = (y - bx * y.dot(bx)).normalized(), swing_z = (z - bx * z.dot(bx)).normalized(), + ra = ra, rb = rb, d = (sb.dp - sa.dp) + r.delta_center + (rb - ra), + }; + # `b`'s frame within `a`'s, as a swing after a twist about x. + var q := (fa.inverse() * fb).normalized(); + if q.w < 0 { + q = quat{ -q.x, -q.y, -q.z, -q.w }; + } + val about := math::sqrt(q.x * q.x + q.w * q.w); + var twist := quat::identity; + if about > tiny { + twist = quat{ q.x / about, 0, 0, q.w / about }; + made.twist = 2 * math::atan2(q.x, q.w); + } + val swing := q * twist.inverse(); + val across := math::sqrt(swing.y * swing.y + swing.z * swing.z); + if across > tiny { + val angle := 2 * math::atan2(across, math::abs(swing.w)); + val sign := swing.w < 0 ? -1f : 1f; + made.swung_y = sign * angle * swing.y / across; + made.swung_z = sign * angle * swing.z / across; + } + return made; +} + +# How hard it is to turn the two apart about an axis of space. +def turning_mass(axis: vec3, ia: mat3, ib: mat3): f32 { + val k := axis.dot((ia + ib) * axis); + return k > 0 ? 1 / k : 0f; +} + +# How hard it is to push the two apart along a direction of space, `a` turning +# about the place of `b`'s anchor, as a slider's axis is `a`'s. +def sliding_mass(u: vec3, f: &joint_frame, r: &joint_record, ia: mat3, ib: mat3): f32 { + val la := (f.ra + f.d).cross(u); + val lb := f.rb.cross(u); + val k := r.ma + r.mb + la.dot(ia * la) + lb.dot(ib * lb); + return k > 0 ? 1 / k : 0f; +} + +# How fast the two part along a direction of space, as a slider's. +def sliding_speed(u: vec3, f: &joint_frame, sa: &body_state, sb: &body_state): f32 { + return u.dot(sb.v - sa.v) + f.rb.cross(u).dot(sb.w) - (f.ra + f.d).cross(u).dot(sa.w); +} + +# Pushes the two apart by an impulse along a slider's direction. +def slide_apart(r: &joint_record, f: &joint_frame, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, p: vec3): void { + sa.v = sa.v - p * r.ma; + sa.w = sa.w - ia * (f.ra + f.d).cross(p); + sb.v = sb.v + p * r.mb; + sb.w = sb.w + ib * f.rb.cross(p); +} + +# A row held still: its impulse toward undoing `c`, where it's drifted, at +# `cdot`, how fast it drifts. +def held_impulse(c: f32, cdot: f32, mass: f32, held: f32, soft: &softness, use_bias: bool): f32 { + if !use_bias { + return -mass * cdot; + } + return -mass * soft.mass_scale * (cdot + soft.bias_rate * c) - soft.impulse_scale * held; +} + +# Each way of a six-way joint, as its frame lies now: its direction, and how +# far it's moved or turned. +def way_of(f: &joint_frame, k: u32): vec3 { + return k == 0 ? f.x : (k == 1 ? f.y : f.z) if k < 3; + return k == 3 ? f.twist_x : (k == 4 ? f.swing_y : f.swing_z); +} + +def amount_of(f: &joint_frame, k: u32): f32 { + return f.d.dot(way_of(f, k)) if k < 3; + return k == 3 ? f.twist : (k == 4 ? f.swung_y : f.swung_z); +} + +# The impulses a slider, a limited ball joint, or a six-way joint ended the last +# substep with, given again, beyond those `warm_joints` gives every joint. +def warm_free(r: &joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3): void { + val f := frame_of(r, sa, sb); + if r.made.kind == joint_kind::slider { + val axial := r.spring_impulse + r.motor_impulse + r.lower_impulse - r.upper_impulse; + slide_apart(r, &f, sa, sb, ia, ib, f.x * axial + f.y * r.held[1] + f.z * r.held[2]); + } else if r.made.kind == joint_kind::ball { + turn_apart(sa, sb, ia, ib, cone_axis(r, &f) * -r.held[0] + f.twist_x * (r.held[1] - r.held[2])); + } else { + for k in 0..6u { + val total := r.held[k] + r.held[6 + k] - r.held[12 + k] + r.held[18 + k]; + continue if total == 0; + if k < 3 { + slide_apart(r, &f, sa, sb, ia, ib, way_of(&f, k as u32) * total); + } else { + turn_apart(sa, sb, ia, ib, way_of(&f, k as u32) * total); + } + } + } +} + +# The axis a ball joint's swing turns about, in space, from `a`'s frame's x to +# `b`'s. +def cone_axis(r: &joint_record, f: &joint_frame): vec3 { + val across := f.x.cross(f.twist_x); + return across.length_squared > tiny * tiny ? across.normalized() : vec3::zero; +} + +# A slider: its turn held as a fixed joint's, its anchors held to its axis, +# and along the axis its motor, spring, and limits. +def solve_slider(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void { + solve_fixed_turn(r, sa, sb, ia, ib, use_bias); + val made := &r.made; + val f := frame_of(r, sa, sb); + val axial_mass := sliding_mass(f.x, &f, r, ia, ib); + val translation := f.d.dot(f.x); + if made.motor { + val most := h * made.max_motor_force; + val held := r.motor_impulse; + r.motor_impulse = math::clamp(held + axial_mass * (made.motor_speed - sliding_speed(f.x, &f, sa, sb)), -most, most); + slide_apart(r, &f, sa, sb, ia, ib, f.x * (r.motor_impulse - held)); + } + if made.spring && made.hertz > 0 { + val impulse := -r.spring_soft.mass_scale * axial_mass * (sliding_speed(f.x, &f, sa, sb) + r.spring_soft.bias_rate * translation) - r.spring_soft.impulse_scale * r.spring_impulse; + r.spring_impulse += impulse; + slide_apart(r, &f, sa, sb, ia, ib, f.x * impulse); + } + if made.limit { + val lower := limit_impulse(translation - made.lower, sliding_speed(f.x, &f, sa, sb), axial_mass, r.lower_impulse, soft, 1 / h, use_bias); + r.lower_impulse += lower; + slide_apart(r, &f, sa, sb, ia, ib, f.x * lower); + val upper := limit_impulse(made.upper - translation, -sliding_speed(f.x, &f, sa, sb), axial_mass, r.upper_impulse, soft, 1 / h, use_bias); + r.upper_impulse += upper; + slide_apart(r, &f, sa, sb, ia, ib, f.x * -upper); + } + # Held to its axis: neither of the directions across it. + for k in 1..3u { + val u := k == 1 ? f.y : f.z; + val impulse := held_impulse(f.d.dot(u), sliding_speed(u, &f, sa, sb), sliding_mass(u, &f, r, ia, ib), r.held[k], soft, use_bias); + r.held[k] += impulse; + slide_apart(r, &f, sa, sb, ia, ib, u * impulse); + } +} + +# A ball joint's limits: its swing within its cone, its twist between its +# lower and upper. +def solve_cone(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void { + val f := frame_of(r, sa, sb); + val made := &r.made; + val swung := math::atan2(f.x.cross(f.twist_x).length, f.x.dot(f.twist_x)); + val axis := cone_axis(r, &f); + if axis.length_squared > 0 { + val swing := limit_impulse(made.cone - swung, (sa.w - sb.w).dot(axis), turning_mass(axis, ia, ib), r.held[0], soft, 1 / h, use_bias); + r.held[0] += swing; + turn_apart(sa, sb, ia, ib, axis * -swing); + } + val mass := turning_mass(f.twist_x, ia, ib); + val lower := limit_impulse(f.twist - made.lower, (sb.w - sa.w).dot(f.twist_x), mass, r.held[1], soft, 1 / h, use_bias); + r.held[1] += lower; + turn_apart(sa, sb, ia, ib, f.twist_x * lower); + val upper := limit_impulse(made.upper - f.twist, (sa.w - sb.w).dot(f.twist_x), mass, r.held[2], soft, 1 / h, use_bias); + r.held[2] += upper; + turn_apart(sa, sb, ia, ib, f.twist_x * -upper); +} + +# A six-way joint: each way driven by its motor, held within its limits, or +# held still, its turns first, then its place; three places locked together +# are held as a ball joint holds its anchors. +def solve_six(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void { + val made := &r.made; + val point := made.holds[0] == axis_hold::locked && made.holds[1] == axis_hold::locked && made.holds[2] == axis_hold::locked; + var k: u32 = 3; + while true { + val f := frame_of(r, sa, sb); + val u := way_of(&f, k); + val amount := amount_of(&f, k); + val sliding := k < 3; + val mass := sliding ? sliding_mass(u, &f, r, ia, ib) : turning_mass(u, ia, ib); + val speed := sliding ? sliding_speed(u, &f, sa, sb) : (sb.w - sa.w).dot(u); + var push: f32 = 0; + if made.holds[k] == axis_hold::locked { + if !sliding || !point { + push = held_impulse(amount, speed, mass, r.held[k], soft, use_bias); + r.held[k] += push; + } + } else { + if made.forces[k] > 0 { + val most := h * made.forces[k]; + val before := r.held[18 + k]; + r.held[18 + k] = math::clamp(before + mass * (made.drives[k] - speed), -most, most); + push += r.held[18 + k] - before; + } + if made.holds[k] == axis_hold::limited { + val lower := limit_impulse(amount - made.lows[k], speed, mass, r.held[6 + k], soft, 1 / h, use_bias); + r.held[6 + k] += lower; + val upper := limit_impulse(made.highs[k] - amount, -speed - lower / math::max(mass, tiny), mass, r.held[12 + k], soft, 1 / h, use_bias); + r.held[12 + k] += upper; + push += lower - upper; + } + } + if push != 0 { + if sliding { + slide_apart(r, &f, sa, sb, ia, ib, u * push); + } else { + turn_apart(sa, sb, ia, ib, u * push); + } + } + # The turns, 3 to 5, then the places, 0 to 2. + k = k == 5 ? 0 as u32 : k + 1; + if k == 3 { + break; + } + } + if point { + solve_point(r, sa, sb, ia, ib, soft, use_bias); + } +} diff --git a/physics3d/heightfield.sakura b/physics3d/heightfield.sakura new file mode 100644 index 0000000..68ecf15 --- /dev/null +++ b/physics3d/heightfield.sakura @@ -0,0 +1,255 @@ +#! Contains `heightfield`, a level's ground as heights on a grid, as terrain is +#! painted: two triangles of each square of four heights, made as they're met +#! rather than kept, so a field of a million heights costs their floats alone. +#! A space keeps one as a `triangle_mesh` keeps its triangles, met a triangle +#! at a time, its edges two triangles share flat or hollow passed over as a +#! mesh's are, so a body rolls across it as along one surface. + +import std::containers; +import std::math; +import malunal::geometry; +import malunal::linear; +module malunal::physics3d; + +#! Heights on a grid along x and z, as a terrain's ground: `columns` along x by +#! `rows` along z, `cell` apart each way, the first at its origin. +pub struct heightfield { + var _columns: u32; + var _rows: u32; + var _cell: vec2; + var _heights: vector; + var _low: f32; + var _high: f32; +} + +#! The heights of a grid of `columns` along x by `rows` along z, a row of +#! columns after another, from the origin toward +z, each `cell` apart along x +#! and z: those missing are 0. Of fewer than two each way, it holds no +#! triangles. +pub def heightfield::new(columns: u32, rows: u32, heights: span, cell: vec2 = vec2{ 1, 1 }): heightfield { + var made := heightfield{ _columns = columns, _rows = rows, _cell = cell, _heights = vector::::new() }; + val count := columns as u64 * rows as u64; + for i in 0..count { + made._heights.append(i < heights.length ? heights[i] : 0f); + } + if count > 0 { + made._low = made._heights[0]; + made._high = made._heights[0]; + for i in 1..count { + made._low = math::min(made._low, made._heights[i]); + made._high = math::max(made._high, made._heights[i]); + } + } + return made; +} + +pub val heightfield::columns: u32 { + get => this._columns; +} + +pub val heightfield::rows: u32 { + get => this._rows; +} + +#! How far apart its heights are along x, and along z. +pub val heightfield::cell: vec2 { + get => this._cell; +} + +#! How many triangles it has: two of each square of four heights. +pub val heightfield::length: u64 { + get => this._columns < 2 || this._rows < 2 ? 0 as u64 : (this._columns - 1) as u64 * (this._rows - 1) as u64 * 2; +} + +#! The height at a column and row. +pub def heightfield::height(&this, column: u32, row: u32): f32 { + return this._heights[row as u64 * this._columns as u64 + column as u64]; +} + +#! The ground's height above a place of its own, between its heights, as its +#! triangles lie: nothing beyond it. +pub def heightfield::height_at(&this, x: f32, z: f32): maybe { + return nothing{} if this.length == 0; + val fx := x / this._cell.x; + val fz := z / this._cell.y; + return nothing{} if fx < 0 || fz < 0 || fx > (this._columns - 1) as f32 || fz > (this._rows - 1) as f32; + val i := math::min(fx as u32, this._columns - 2); + val j := math::min(fz as u32, this._rows - 2); + val u := fx - i as f32; + val v := fz - j as f32; + val h00 := this.height(i, j); + val h10 := this.height(i + 1, j); + val h01 := this.height(i, j + 1); + val h11 := this.height(i + 1, j + 1); + return h00 + (h10 - h00) * u + (h01 - h00) * v if u + v <= 1; + return h11 + (h01 - h11) * (1 - u) + (h10 - h11) * (1 - v); +} + +#! The box holding it, of its own places. +pub val heightfield::bounds: bounds { + get => bounds{ + vec3{ 0, this._low, 0 }, + vec3{ math::max(this._columns, 1 as u32) as f32 * this._cell.x - this._cell.x, this._high, math::max(this._rows, 1 as u32) as f32 * this._cell.y - this._cell.y }, + }; +} + +# The place of a height, of its own places. +def heightfield::corner(&this, i: u32, j: u32): vec3 { + return vec3{ i as f32 * this._cell.x, this.height(i, j), j as f32 * this._cell.y }; +} + +# Triangle `t` is of the square at column `i` and row `j`, its first half or +# its second. +def heightfield::triangle_of(&this, i: u32, j: u32, half: u32): u32 { + return (j * (this._columns - 1) + i) * 2 + half; +} + +#! A triangle's corners, counterclockwise as they're seen from above: of each +#! square, the half by its first corner, then the half by its last. +pub def heightfield::triangle(&this, t: u32): vec3[3] { + val square := t / 2; + val i := square % (this._columns - 1); + val j := square / (this._columns - 1); + return [this.corner(i, j), this.corner(i, j + 1), this.corner(i + 1, j)] if t % 2 == 0; + return [this.corner(i + 1, j), this.corner(i, j + 1), this.corner(i + 1, j + 1)]; +} + +#! The way a triangle faces. +pub def heightfield::normal(&this, t: u32): vec3 { + val c := this.triangle(t); + return (c[1] - c[0]).cross(c[2] - c[0]).normalized(); +} + +# Which of a triangle's edges push as they meet, a bit each, as a mesh's: those +# its neighbor shares flat or hollow don't. +def heightfield::active(&this, t: u32): u8 { + val square := t / 2; + val i := square % (this._columns - 1); + val j := square / (this._columns - 1); + val c := this.triangle(t); + val n := this.normal(t); + var bits: u8 = 7; + for k in 0..3u { + var other: i64 = -1; + var off := vec3::zero; + if t % 2 == 0 { + if k == 0 && i > 0 { + other = this.triangle_of(i - 1, j, 1) as i64; + off = this.corner(i - 1, j + 1); + } else if k == 1 { + other = this.triangle_of(i, j, 1) as i64; + off = this.corner(i + 1, j + 1); + } else if k == 2 && j > 0 { + other = this.triangle_of(i, j - 1, 1) as i64; + off = this.corner(i + 1, j - 1); + } + } else { + if k == 0 { + other = this.triangle_of(i, j, 0) as i64; + off = this.corner(i, j); + } else if k == 1 && j + 2 < this._rows { + other = this.triangle_of(i, j + 1, 0) as i64; + off = this.corner(i, j + 2); + } else if k == 2 && i + 2 < this._columns { + other = this.triangle_of(i + 1, j, 0) as i64; + off = this.corner(i + 2, j); + } + } + continue if other < 0; + val ridged := n.dot(off - c[k]) < 0 && n.dot(this.normal(other as u32)) < ridge; + if !ridged { + bits = without_bit(bits, k as u64); + } + } + return bits; +} + +# The columns or rows of squares a span of its own places reaches, within it. +def square_span(low: f32, high: f32, size: f32, squares: u32): i64[2] { + val first := math::max(math::floor(low / size) as i64, (0 as i64)); + val last := math::min(math::floor(high / size) as i64, squares as i64 - 1); + return [first, last]; +} + +#! Visits each triangle whose square a box of its own places reaches, as +#! `visit(triangle)`, until it gives false. +pub def heightfield::triangles_in(&this, box: bounds, visit: F): void where F: invokable { + return if this.length == 0 || box.max.y < this._low || box.min.y > this._high; + val xs := square_span(box.min.x, box.max.x, this._cell.x, this._columns - 1); + val zs := square_span(box.min.z, box.max.z, this._cell.y, this._rows - 1); + var j := zs[0]; + while j <= zs[1] { + var i := xs[0]; + while i <= xs[1] { + for half in 0..2u { + return if !visit(this.triangle_of(i as u32, j as u32, half as u32)); + } + i++; + } + j++; + } +} + +# Where a ray, of its own places, first meets a triangle, passed from square to +# square along x and z as Amanatides and Woo pass one: the first square it +# meets a triangle of holds the nearest. +def heightfield::ray_cast(&this, o: vec3, d: vec3, reach: f32): maybe { + return nothing{} if this.length == 0; + val box := this.bounds; + var enter: f32 = 0; + var leave := reach; + val lows: f32[3] = [box.min.x, box.min.y, box.min.z]; + val highs: f32[3] = [box.max.x, box.max.y, box.max.z]; + val os: f32[3] = [o.x, o.y, o.z]; + val ds: f32[3] = [d.x, d.y, d.z]; + for k in 0..3u { + if math::abs(ds[k]) < tiny { + return nothing{} if os[k] < lows[k] || os[k] > highs[k]; + } else { + val t1 := (lows[k] - os[k]) / ds[k]; + val t2 := (highs[k] - os[k]) / ds[k]; + enter = math::max(enter, math::min(t1, t2)); + leave = math::min(leave, math::max(t1, t2)); + return nothing{} if enter > leave; + } + } + val start := o + d * enter; + val squares_x := (this._columns - 1) as i64; + val squares_z := (this._rows - 1) as i64; + var i := math::clamp(math::floor(start.x / this._cell.x) as i64, (0 as i64), squares_x - 1); + var j := math::clamp(math::floor(start.z / this._cell.y) as i64, (0 as i64), squares_z - 1); + val step_x: i64 = d.x > 0 ? 1 : -1; + val step_z: i64 = d.z > 0 ? 1 : -1; + val far := 1e30f; + var next_x := math::abs(d.x) < tiny ? far : (((i + (d.x > 0 ? (1 as i64) : (0 as i64))) as f32) * this._cell.x - o.x) / d.x; + var next_z := math::abs(d.z) < tiny ? far : (((j + (d.z > 0 ? (1 as i64) : (0 as i64))) as f32) * this._cell.y - o.z) / d.z; + val across_x := math::abs(d.x) < tiny ? far : this._cell.x / math::abs(d.x); + val across_z := math::abs(d.z) < tiny ? far : this._cell.y / math::abs(d.z); + while i >= 0 && j >= 0 && i < squares_x && j < squares_z { + var best: maybe = nothing{}; + var nearest := reach; + for half in 0..2u { + val t := this.triangle_of(i as u32, j as u32, half as u32); + val c := this.triangle(t); + if ray_triangle(o, d, c[0], c[1], c[2]) is some(along) { + if along <= nearest { + nearest = along; + val n := this.normal(t); + best = mesh_hit{ distance = along, point = o + d * along, normal = n.dot(d) <= 0 ? n : -n, triangle = t }; + } + } + } + return best if best is some(_); + if math::min(next_x, next_z) > leave { + break; + } + if next_x < next_z { + i += step_x; + next_x += across_x; + } else { + j += step_z; + next_z += across_z; + } + } + return nothing{}; +} diff --git a/physics3d/hull.sakura b/physics3d/hull.sakura new file mode 100644 index 0000000..abc8001 --- /dev/null +++ b/physics3d/hull.sakura @@ -0,0 +1,509 @@ +#! Contains `hull`, a convex polyhedron: its corners; its faces, each a convex +#! polygon of its corners, counterclockwise as it's seen from outside, its +#! normal facing out; and its edges, each between two faces. It's made as a box, +#! as a triangle, flat, with a face each way, or around places, as the least +#! hull holding them, each of its faces as many of their triangles as lie in one +#! plane. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics3d; + +#! The most corners a hull has. +pub const max_hull_points: u32 = 32; + +# The most faces and edges a hull of so many corners has, as Euler's formula +# bounds them: 2V - 4 faces and 3V - 6 edges, each edge a corner of two faces. +const max_hull_faces: u32 = 60; +const max_hull_edges: u32 = 90; + +# Faces whose normals are nearer one another than this are one face. +const coplanar: f32 = 0.9999; + +#! A convex polyhedron, about the origin of its body, as plain data, so a shape +#! holding one is copied whole. +pub struct hull { + var _count: u32; + var _faces: u32; + var _edges: u32; + var _points: vec3[32]; + var _normals: vec3[60]; + var _first: u8[60]; # Of each face, where its corners begin in `_corners`. + var _sizes: u8[60]; # Of each face, how many corners. + var _corners: u8[180]; # Each face's corners, counterclockwise from outside. + var _ends: u8[180]; # Each edge's two corners. + var _sides: u8[180]; # Each edge's two faces. + var _center: vec3; +} + +#! A box reaching so far each way from its middle, about a place, turned by a +#! rotation. +pub def hull::box(half: vec3, center: vec3 = vec3::zero, turn: quat = quat::identity): hull { + var made := hull{ _count = 8, _faces = 6 }; + val m := mat3::rotation(turn); + # Corner `i` is on the high side of x where bit 0 is set, of y where bit 1 + # is, and of z where bit 2 is. + for i in 0..8u { + val corner := vec3{ (i & 1) != 0 ? half.x : -half.x, (i & 2) != 0 ? half.y : -half.y, (i & 4) != 0 ? half.z : -half.z }; + made._points[i] = center + m * corner; + } + val loops: u8[24] = [1, 3, 7, 5, 0, 4, 6, 2, 2, 6, 7, 3, 0, 1, 5, 4, 4, 5, 7, 6, 0, 2, 3, 1]; + for i in 0..24u { + made._corners[i] = loops[i]; + } + for f in 0..6u { + made._first[f] = (f * 4) as u8; + made._sizes[f] = 4; + } + made.finish(); + return made; +} + +#! A triangle of three places, flat: a face each way, the first facing where +#! they turn counterclockwise, and three edges, each between the two faces. +pub def hull::triangle(a: vec3, b: vec3, c: vec3): hull { + var made := hull{ _count = 3, _faces = 2 }; + made._points[0] = a; + made._points[1] = b; + made._points[2] = c; + val loops: u8[6] = [0, 1, 2, 0, 2, 1]; + for i in 0..6u { + made._corners[i] = loops[i]; + } + made._first[1] = 3; + made._sizes[0] = 3; + made._sizes[1] = 3; + made.finish(); + return made; +} + +# A triangle of the hull being made, by its corners' indices among the places. +struct building { + var a: u32; + var b: u32; + var c: u32; + var normal: vec3; + var offset: f32; + var alive: bool; +} + +def building_of(places: span, a: u32, b: u32, c: u32): building { + val normal := (places[b] - places[a]).cross(places[c] - places[a]).normalized(); + return building{ a = a, b = b, c = c, normal = normal, offset = normal.dot(places[a]), alive = true }; +} + +# A place, and how far it is from the middle of the first four corners, by +# which the furthest are put on first. +struct by_reach { + var reach: f32; + var index: u32; +} + +def further(x: &by_reach, y: &by_reach): bool { + return x.reach > y.reach; +} + +#! The least convex hull holding places: what's within it, or on its faces, +#! left out. Nothing where the places hold no volume, or their hull has more +#! than `max_hull_points` corners. +pub def hull::of(places: span): maybe { + return nothing{} if places.length < 4; + # How near a place is to a face to be taken as on it, of the places' size. + var low := places[0]; + var high := places[0]; + for i in 1..places.length { + low = low.min(places[i]); + high = high.max(places[i]); + } + val reach := low.abs().max(high.abs()); + val near := (reach.x + reach.y + reach.z) * 4e-6 + tiny; + + # The first four corners: the place furthest left, the one furthest from + # it, the one furthest from the line of those, and the one furthest from + # the plane of the three. + var i0: u32 = 0; + for i in 1..places.length { + if places[i].x < places[i0 as u64].x { + i0 = i as u32; + } + } + var i1 := i0; + var best: f32 = 0; + for i in 0..places.length { + val d := (places[i] - places[i0 as u64]).length; + if d > best { + best = d; + i1 = i as u32; + } + } + return nothing{} if best <= near; + val along := (places[i1 as u64] - places[i0 as u64]).normalized(); + var i2 := i0; + best = 0; + for i in 0..places.length { + val d := (places[i] - places[i0 as u64]).cross(along).length; + if d > best { + best = d; + i2 = i as u32; + } + } + return nothing{} if best <= near; + val facing := (places[i1 as u64] - places[i0 as u64]).cross(places[i2 as u64] - places[i0 as u64]).normalized(); + var i3 := i0; + best = 0; + var side: f32 = 0; + for i in 0..places.length { + val d := facing.dot(places[i] - places[i0 as u64]); + if math::abs(d) > best { + best = math::abs(d); + side = d; + i3 = i as u32; + } + } + return nothing{} if best <= near; + + # The first face faces away from the fourth corner. + var a := i0; + var b := i1; + var c := i2; + if side > 0 { + b = i2; + c = i1; + } + var faces := vector::::new(); + faces.append(building_of(places, a, b, c)); + faces.append(building_of(places, a, i3, b)); + faces.append(building_of(places, b, i3, c)); + faces.append(building_of(places, c, i3, a)); + + # The rest, the furthest from the middle first, each outside the hull so + # far replacing the faces it sees with faces from their horizon to it. + val middle := (places[i0 as u64] + places[i1 as u64] + places[i2 as u64] + places[i3 as u64]) * 0.25; + var order := vector::::new(); + for i in 0..places.length { + order.append(by_reach{ reach = (places[i] - middle).length_squared, index = i as u32 }); + } + order.sort_by(further); + var seen := vector::::new(); + for k in 0..order.length { + val p := order[k].index; + val place := places[p as u64]; + # The directed edges of the faces it sees. + seen.clear(); + for f in 0..faces.length { + continue if !faces[f].alive || faces[f].normal.dot(place) - faces[f].offset <= near; + faces[f].alive = false; + seen.append(edge_key(faces[f].a, faces[f].b)); + seen.append(edge_key(faces[f].b, faces[f].c)); + seen.append(edge_key(faces[f].c, faces[f].a)); + } + continue if seen.empty; + # An edge seen one way only is on the horizon. + val count := seen.length; + for e in 0..count { + val key := seen[e]; + val from := (key >> 32) as u32; + val to := (key & 0xFFFFFFFF) as u32; + var shared := false; + for o in 0..count { + if seen[o] == edge_key(to, from) { + shared = true; + break; + } + } + if !shared { + faces.append(building_of(places, from, to, p)); + } + } + } + return hull::of_triangles(places, faces.span); +} + +def edge_key(from: u32, to: u32): u64 { + return ((from as u64) << 32) | to as u64; +} + +# The hull of the triangles left: those in one plane made one face, the +# corners they use numbered from 0. +def hull::of_triangles(places: span, faces: span): maybe { + # Which triangle lies across each directed edge. + var across := dict::::new(); + var alive := vector::::new(); + for f in 0..faces.length { + continue if !faces[f].alive; + alive.append(f); + across.set(edge_key(faces[f].a, faces[f].b), f); + across.set(edge_key(faces[f].b, faces[f].c), f); + across.set(edge_key(faces[f].c, faces[f].a), f); + } + # Each triangle's face: those reached from it across edges, facing as it + # does. + var group := vector::::new(); + for f in 0..faces.length { + group.append(-1); + } + var made := hull{}; + var numbered := dict::::new(); + var corners: u32 = 0; + var pending := vector::::new(); + var edges := vector::::new(); + var ring := dict::::new(); + for k in 0..alive.length { + val seed := alive[k]; + # A triangle of no area takes the face of one beside it. + continue if group[seed] >= 0 || faces[seed].normal.length_squared < 0.25; + return nothing{} if made._faces >= max_hull_faces; + val face := made._faces; + val normal := faces[seed].normal; + group[seed] = face as i64; + pending.clear(); + pending.append(seed); + edges.clear(); + while !pending.empty { + val t := pending[pending.length - 1]; + pending.truncate(); + val keys: u64[3] = [edge_key(faces[t].a, faces[t].b), edge_key(faces[t].b, faces[t].c), edge_key(faces[t].c, faces[t].a)]; + for e in 0..3u { + edges.append(keys[e]); + val reverse := edge_key((keys[e] & 0xFFFFFFFF) as u32, (keys[e] >> 32) as u32); + if across.get(&reverse) is some(&other) { + val o: u64 = other; + if group[o] < 0 && (faces[o].normal.dot(normal) > coplanar || faces[o].normal.length_squared < 0.25) { + group[o] = face as i64; + pending.append(o); + } + } + } + } + # The face's boundary: its triangles' edges whose reverse isn't among + # them, walked from one to the next. + ring.clear(); + var start: u32 = 0; + var length: u32 = 0; + for e in 0..edges.length { + val from := (edges[e] >> 32) as u32; + val to := (edges[e] & 0xFFFFFFFF) as u32; + var inner := false; + for o in 0..edges.length { + if edges[o] == edge_key(to, from) { + inner = true; + break; + } + } + if !inner { + ring.set(from, to); + start = from; + length++; + } + } + val first := made.corner_total(); + return nothing{} if first + length > max_hull_edges * 2; + var at := start; + var walked: u32 = 0; + var newell := vec3::zero; + while walked < length { + if numbered.get(&at) is none { + return nothing{} if corners >= max_hull_points; + made._points[corners] = places[at as u64]; + numbered.set(at, corners); + corners++; + } + if numbered.get(&at) is some(&n) { + val number: u32 = n; + made._corners[first + walked] = number as u8; + } + var next := at; + if ring.get(&at) is some(&n) { + next = n; + } else { + return nothing{}; + } + newell = newell + places[at as u64].cross(places[next as u64]); + at = next; + walked++; + break if at == start; + } + return nothing{} if walked != length || walked < 3; + made._first[face] = first as u8; + made._sizes[face] = walked as u8; + made._normals[face] = newell.normalized(); + made._faces++; + } + made._count = corners; + return nothing{} if !made.find_edges(); + made.find_center(); + return made; +} + +# How many corners its faces have in all. +def hull::corner_total(&this): u32 { + var total: u32 = 0; + for f in 0..this._faces { + total += this._sizes[f] as u32; + } + return total; +} + +# Finds its normals, edges, and middle, of its corners and faces. +def hull::finish(&mut this): void { + for f in 0..this._faces { + var newell := vec3::zero; + for k in 0..this.face_size(f) { + newell = newell + this.point(this.corner(f, k)).cross(this.point(this.corner(f, (k + 1) % this.face_size(f)))); + } + this._normals[f] = newell.normalized(); + } + _ = this.find_edges(); + this.find_center(); +} + +# Finds its edges, each once, and the two faces either side, of its faces' +# corners: an edge from a lesser corner to a greater in one face, and back in +# the other. Gives false where one isn't, as a hull with a hole. +def hull::find_edges(&mut this): bool { + this._edges = 0; + for f in 0..this._faces { + val size := this.face_size(f); + for k in 0..size { + val from := this.corner(f, k); + val to := this.corner(f, (k + 1) % size); + continue if from > to; + return false if this._edges >= max_hull_edges; + val e := this._edges; + this._ends[e * 2] = from as u8; + this._ends[e * 2 + 1] = to as u8; + this._sides[e * 2] = f as u8; + this._sides[e * 2 + 1] = 0xFF; + this._edges++; + } + } + for f in 0..this._faces { + val size := this.face_size(f); + for k in 0..size { + val from := this.corner(f, k); + val to := this.corner(f, (k + 1) % size); + continue if from < to; + for e in 0..this._edges { + if this._ends[e * 2] as u32 == to && this._ends[e * 2 + 1] as u32 == from { + this._sides[e * 2 + 1] = f as u8; + break; + } + } + } + } + for e in 0..this._edges { + return false if this._sides[e * 2 + 1] == 0xFF; + } + return true; +} + +def hull::find_center(&mut this): void { + var sum := vec3::zero; + for i in 0..this._count { + sum = sum + this._points[i]; + } + this._center = sum * (1 / this._count as f32); +} + +#! How many corners it has. +pub val hull::count: u32 { + get => this._count; +} + +#! A corner. +pub def hull::point(&this, i: u32): vec3 { + return this._points[i]; +} + +#! How many faces it has. +pub val hull::faces: u32 { + get => this._faces; +} + +#! A face's normal, facing out. +pub def hull::normal(&this, face: u32): vec3 { + return this._normals[face]; +} + +#! How many corners a face has. +pub def hull::face_size(&this, face: u32): u32 { + return this._sizes[face] as u32; +} + +#! Which corner is a face's `k`th, counterclockwise from outside. +pub def hull::corner(&this, face: u32, k: u32): u32 { + return this._corners[this._first[face] as u32 + k] as u32; +} + +#! How far its plane is along a face's normal from the origin. +pub def hull::offset(&this, face: u32): f32 { + return this._normals[face].dot(this.point(this.corner(face, 0))); +} + +#! How many edges it has. +pub val hull::edges: u32 { + get => this._edges; +} + +#! An edge's corners, the lesser first. +pub def hull::edge(&this, e: u32): u32[2] { + return [this._ends[e * 2] as u32, this._ends[e * 2 + 1] as u32]; +} + +#! The faces either side of an edge. +pub def hull::edge_faces(&this, e: u32): u32[2] { + return [this._sides[e * 2] as u32, this._sides[e * 2 + 1] as u32]; +} + +#! The middle of its corners, which is within it. +pub val hull::center: vec3 { + get => this._center; +} + +#! Whether it's flat, of two faces, as a triangle is. +pub val hull::is_flat: bool { + get => this._faces == 2; +} + +#! The corner furthest along a direction. +pub def hull::support(&this, direction: vec3): u32 { + var found: u32 = 0; + var most := this._points[0].dot(direction); + for i in 1..this._count { + val d := this._points[i].dot(direction); + if d > most { + most = d; + found = i; + } + } + return found; +} + +#! The hull scaled along each axis, as a transform scales what it holds: its +#! normals turned as the faces they're of are. +pub def hull::scaled(&this, by: vec3): hull { + var made: hull = this; + for i in 0..this._count { + made._points[i] = this._points[i] * by; + } + for f in 0..this._faces { + made._normals[f] = (this._normals[f] / by).normalized(); + } + made._center = this._center * by; + return made; +} + +#! The hull moved and turned as a pose places it. +pub def hull::moved(&this, by: pose): hull { + var made: hull = this; + val m := mat3::rotation(by.turn); + for i in 0..this._count { + made._points[i] = by.at + m * this._points[i]; + } + for f in 0..this._faces { + made._normals[f] = m * this._normals[f]; + } + made._center = by.at + m * this._center; + return made; +} diff --git a/physics3d/joint_solver.sakura b/physics3d/joint_solver.sakura new file mode 100644 index 0000000..c34dd81 --- /dev/null +++ b/physics3d/joint_solver.sakura @@ -0,0 +1,324 @@ +#! Contains how a step solves joints, as Box2D's soft step solves them: each +#! is prepared as the step begins, begins each substep with the impulses it +#! ended the last with, and pushes its bodies' velocities toward holding it, +#! undoing drift softly where `use_bias` asks. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics3d; + +def space::prepare_joints(&mut this, s: &mut solver_scratch, h: f32): void { + s.joints.clear(); + s.joint_soft = soft_of(this.joint_hertz, this.joint_damping, h); + for j in 0..this.joints.length { + continue if !this.joints[j].alive; + var r := this.joints[j]; + val a := &this.bodies[r.body_a as u64]; + val b := &this.bodies[r.body_b as u64]; + continue if a.slot == 0 && b.slot == 0; + s.joints.append(j as u32); + r.slot_a = a.slot; + r.slot_b = b.slot; + r.ma = a.inv_mass; + r.mb = b.inv_mass; + r.qa = a.at.turn; + r.qb = b.at.turn; + r.ra = a.at.turn * (r.made.anchor_a - a.local_center); + r.rb = b.at.turn * (r.made.anchor_b - b.local_center); + r.delta_center = b.center - a.center; + val ia := s.inertias[a.slot as u64]; + val ib := s.inertias[b.slot as u64]; + if r.made.kind == joint_kind::distance { + r.axial_mass = mass_along((r.rb - r.ra + r.delta_center).normalized(), r.ra, r.rb, r.ma, r.mb, ia, ib); + } else { + # A hinge turns each body about its axis through the anchor, not about + # its center, as the point it's held at keeps it: how hard that is is its + # moment about the axis, and its mass as far from the axis as its center + # is, so a limit stops a door outright rather than leaving the point to + # turn it back. + val axis := r.qa * r.made.axis_a; + val k := about_hinge(a, axis, r.ra) + about_hinge(b, axis, r.rb); + r.axial_mass = k > 0 ? 1 / k : 0f; + } + r.spring_soft = soft_of(r.made.hertz, r.made.damping, h); + r.linear_soft = r.made.hertz == 0 ? s.joint_soft : soft_of(r.made.hertz, r.made.damping, h); + r.angular_soft = r.made.angular_hertz == 0 ? s.joint_soft : soft_of(r.made.angular_hertz, r.made.angular_damping, h); + this.joints[j] = r; + } +} + +# How easily a body turns about an axis through a place `r` from its center: +# the inverse of its moment about it. +def about_hinge(b: &body_record, axis: vec3, r: vec3): f32 { + return 0 if b.inv_mass == 0 || b.fixed_rotation; + val turn := mat3::rotation(b.at.turn); + val inertia := turn * b.inertia * turn.transposed(); + val across := r.length_squared - r.dot(axis) * r.dot(axis); + val moment := axis.dot(inertia * axis) + b.mass * across; + return moment > 0 ? 1 / moment : 0f; +} + +# A hinge's axis as each body is turned now, and two directions across it. +struct hinge_axes { + var a1: vec3; + var a2: vec3; + var u1: vec3; + var u2: vec3; +} + +def axes_of(r: &joint_record, sa: &body_state, sb: &body_state): hinge_axes { + val a1 := (sa.dq * r.qa).normalized() * r.made.axis_a; + val a2 := (sb.dq * r.qb).normalized() * r.made.axis_b; + val u1 := perpendicular_to(a1); + return hinge_axes{ a1 = a1, a2 = a2, u1 = u1, u2 = a1.cross(u1) }; +} + +def space::warm_joints(&mut this, s: &mut solver_scratch): void { + for i in 0..s.joints.length { + val r := &this.joints[s.joints[i] as u64]; + var sa := s.states[r.slot_a as u64]; + var sb := s.states[r.slot_b as u64]; + val ia := s.inertias[r.slot_a as u64]; + val ib := s.inertias[r.slot_b as u64]; + val ra := sa.dq * r.ra; + val rb := sb.dq * r.rb; + var p := r.linear; + var turn := vec3::zero; + if r.made.kind == joint_kind::hinge { + val axes := axes_of(r, &sa, &sb); + turn = axes.u1 * r.angular.x + axes.u2 * r.angular.y + axes.a1 * (r.spring_impulse + r.motor_impulse + r.lower_impulse - r.upper_impulse); + } else if r.made.kind == joint_kind::fixed || r.made.kind == joint_kind::slider { + turn = r.angular; + } else if r.made.kind == joint_kind::distance { + val axis := ((sb.dp - sa.dp) + r.delta_center + (rb - ra)).normalized(); + p = axis * (r.axial + r.spring_impulse + r.lower_impulse - r.upper_impulse + r.motor_impulse); + } + sa.v = sa.v - p * r.ma; + sa.w = sa.w - ia * (ra.cross(p) + turn); + sb.v = sb.v + p * r.mb; + sb.w = sb.w + ib * (rb.cross(p) + turn); + if r.made.kind == joint_kind::slider || r.made.kind == joint_kind::six_dof || (r.made.kind == joint_kind::ball && r.made.limit) { + warm_free(r, &mut sa, &mut sb, ia, ib); + } + s.states[r.slot_a as u64] = sa; + s.states[r.slot_b as u64] = sb; + } +} + +def space::solve_joints(&mut this, s: &mut solver_scratch, h: f32, use_bias: bool): void { + for i in 0..s.joints.length { + val j := s.joints[i] as u64; + var r := this.joints[j]; + var sa := s.states[r.slot_a as u64]; + var sb := s.states[r.slot_b as u64]; + val ia := s.inertias[r.slot_a as u64]; + val ib := s.inertias[r.slot_b as u64]; + if r.made.kind == joint_kind::ball { + if r.made.limit { + solve_cone(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias); + } + solve_point(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, use_bias); + } else if r.made.kind == joint_kind::slider { + solve_slider(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias); + } else if r.made.kind == joint_kind::six_dof { + solve_six(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias); + } else if r.made.kind == joint_kind::hinge { + solve_hinge(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias); + solve_point(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, use_bias); + } else if r.made.kind == joint_kind::fixed { + solve_fixed_turn(&mut r, &mut sa, &mut sb, ia, ib, use_bias); + solve_point(&mut r, &mut sa, &mut sb, ia, ib, &r.linear_soft, use_bias || r.made.hertz > 0); + } else { + solve_distance(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias); + } + this.joints[j] = r; + s.states[r.slot_a as u64] = sa; + s.states[r.slot_b as u64] = sb; + } +} + +# The matrix taking a vector to `r`'s cross product with it. +def skew(r: vec3): mat3 { + return mat3{ vec3{ 0, r.z, -r.y }, vec3{ -r.z, 0, r.x }, vec3{ r.y, -r.x, 0 } }; +} + +# Turns the two apart by an angular impulse. +def turn_apart(sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, impulse: vec3): void { + sa.w = sa.w - ia * impulse; + sb.w = sb.w + ib * impulse; +} + +# Pushes the two apart by an impulse at their anchors. +def push_apart(r: &joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, ra: vec3, rb: vec3, p: vec3): void { + sa.v = sa.v - p * r.ma; + sa.w = sa.w - ia * ra.cross(p); + sb.v = sb.v + p * r.mb; + sb.w = sb.w + ib * rb.cross(p); +} + +# A one-sided limit's impulse, as a contact's: of `c` how far it is from +# closing, and `cdot` how fast it closes. +def limit_impulse(c: f32, cdot: f32, mass: f32, held: f32, soft: &softness, inv_h: f32, use_bias: bool): f32 { + var bias: f32 = 0; + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if c > 0 { + bias = c * inv_h; + } else if use_bias { + bias = soft.bias_rate * c; + mass_scale = soft.mass_scale; + impulse_scale = soft.impulse_scale; + } + val impulse := -mass * mass_scale * (cdot + bias) - impulse_scale * held; + return math::max(held + impulse, 0f) - held; +} + +# Holds two anchors at one point. +def solve_point(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, use_bias: bool): void { + val ra := sa.dq * r.ra; + val rb := sb.dq * r.rb; + val cdot := sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra); + var bias := vec3::zero; + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if use_bias { + bias = ((sb.dp - sa.dp) + (rb - ra) + r.delta_center) * soft.bias_rate; + mass_scale = soft.mass_scale; + impulse_scale = soft.impulse_scale; + } + val sa_skew := skew(ra); + val sb_skew := skew(rb); + val k := sa_skew * ia * sa_skew.transposed() + sb_skew * ib * sb_skew.transposed() + + mat3{ vec3{ r.ma + r.mb, 0, 0 }, vec3{ 0, r.ma + r.mb, 0 }, vec3{ 0, 0, r.ma + r.mb } }; + return if k.determinant == 0; + val impulse := (k.inverse() * (cdot + bias)) * -mass_scale - r.linear * impulse_scale; + r.linear = r.linear + impulse; + push_apart(r, sa, sb, ia, ib, ra, rb, impulse); +} + +# Holds a hinge's axes together, and turns it by its spring, its motor, and +# its limits. +def solve_hinge(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void { + val made := &r.made; + val axes := axes_of(r, sa, sb); + if made.spring || made.motor || made.limit { + val angle := hinge_angle(made, (sa.dq * r.qa).normalized(), (sb.dq * r.qb).normalized()); + if made.spring && made.hertz > 0 { + val bias := r.spring_soft.bias_rate * angle; + val impulse := -r.spring_soft.mass_scale * r.axial_mass * ((sb.w - sa.w).dot(axes.a1) + bias) - r.spring_soft.impulse_scale * r.spring_impulse; + r.spring_impulse += impulse; + turn_apart(sa, sb, ia, ib, axes.a1 * impulse); + } + if made.motor { + val most := h * made.max_motor_force; + val held := r.motor_impulse; + r.motor_impulse = math::clamp(held - r.axial_mass * ((sb.w - sa.w).dot(axes.a1) - made.motor_speed), -most, most); + turn_apart(sa, sb, ia, ib, axes.a1 * (r.motor_impulse - held)); + } + if made.limit { + val lower := limit_impulse(angle - made.lower, (sb.w - sa.w).dot(axes.a1), r.axial_mass, r.lower_impulse, soft, 1 / h, use_bias); + r.lower_impulse += lower; + turn_apart(sa, sb, ia, ib, axes.a1 * lower); + val upper := limit_impulse(made.upper - angle, (sa.w - sb.w).dot(axes.a1), r.axial_mass, r.upper_impulse, soft, 1 / h, use_bias); + r.upper_impulse += upper; + turn_apart(sa, sb, ia, ib, axes.a1 * -upper); + } + } + # The axes held together: no turning across them, and what they've drifted + # apart undone. + val both := ia + ib; + val k11 := axes.u1.dot(both * axes.u1); + val k12 := axes.u1.dot(both * axes.u2); + val k22 := axes.u2.dot(both * axes.u2); + val turning := sb.w - sa.w; + var cx := turning.dot(axes.u1); + var cy := turning.dot(axes.u2); + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if use_bias { + val drift := axes.a1.cross(axes.a2); + cx += soft.bias_rate * drift.dot(axes.u1); + cy += soft.bias_rate * drift.dot(axes.u2); + mass_scale = soft.mass_scale; + impulse_scale = soft.impulse_scale; + } + var det := k11 * k22 - k12 * k12; + return if det == 0; + det = 1 / det; + val ix := -mass_scale * det * (k22 * cx - k12 * cy) - impulse_scale * r.angular.x; + val iy := -mass_scale * det * (k11 * cy - k12 * cx) - impulse_scale * r.angular.y; + r.angular = vec3{ r.angular.x + ix, r.angular.y + iy, 0 }; + turn_apart(sa, sb, ia, ib, axes.u1 * ix + axes.u2 * iy); +} + +# Holds a fixed joint's turn: `b` turned within `a` as it rests. +def solve_fixed_turn(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, use_bias: bool): void { + val turning := sb.w - sa.w; + var bias := vec3::zero; + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if use_bias || r.made.angular_hertz > 0 { + val target := (sa.dq * r.qa).normalized() * r.made.reference; + var off := ((sb.dq * r.qb).normalized() * target.inverse()).normalized(); + if off.w < 0 { + off = quat{ -off.x, -off.y, -off.z, -off.w }; + } + bias = vec3{ 2 * off.x, 2 * off.y, 2 * off.z } * r.angular_soft.bias_rate; + mass_scale = r.angular_soft.mass_scale; + impulse_scale = r.angular_soft.impulse_scale; + } + val k := ia + ib; + return if k.determinant == 0; + val impulse := (k.inverse() * (turning + bias)) * -mass_scale - r.angular * impulse_scale; + r.angular = r.angular + impulse; + turn_apart(sa, sb, ia, ib, impulse); +} + +def solve_distance(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void { + val made := &r.made; + val ra := sa.dq * r.ra; + val rb := sb.dq * r.rb; + val d := (sb.dp - sa.dp) + r.delta_center + (rb - ra); + val length := d.length; + val axis := d.normalized(); + if made.spring && (!made.limit || made.lower < made.upper) { + if made.hertz > 0 { + val cdot := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra)); + val bias := r.spring_soft.bias_rate * (length - made.length); + val impulse := -r.spring_soft.mass_scale * r.axial_mass * (cdot + bias) - r.spring_soft.impulse_scale * r.spring_impulse; + r.spring_impulse += impulse; + push_apart(r, sa, sb, ia, ib, ra, rb, axis * impulse); + } + } else { + val cdot := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra)); + var bias: f32 = 0; + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if use_bias { + bias = soft.bias_rate * (length - made.length); + mass_scale = soft.mass_scale; + impulse_scale = soft.impulse_scale; + } + val impulse := -mass_scale * r.axial_mass * (cdot + bias) - impulse_scale * r.axial; + r.axial += impulse; + push_apart(r, sa, sb, ia, ib, ra, rb, axis * impulse); + } + if made.limit && made.lower < made.upper { + val closing := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra)); + val lower := limit_impulse(length - made.lower, closing, r.axial_mass, r.lower_impulse, soft, 1 / h, use_bias); + r.lower_impulse += lower; + push_apart(r, sa, sb, ia, ib, ra, rb, axis * lower); + val opening := axis.dot(sa.v + sa.w.cross(ra) - sb.v - sb.w.cross(rb)); + val upper := limit_impulse(made.upper - length, opening, r.axial_mass, r.upper_impulse, soft, 1 / h, use_bias); + r.upper_impulse += upper; + push_apart(r, sa, sb, ia, ib, ra, rb, axis * -upper); + } + if made.motor { + val most := h * made.max_motor_force; + val held := r.motor_impulse; + val cdot := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra)); + r.motor_impulse = math::clamp(held + r.axial_mass * (made.motor_speed - cdot), -most, most); + push_apart(r, sa, sb, ia, ib, ra, rb, axis * (r.motor_impulse - held)); + } +} diff --git a/physics3d/joints.sakura b/physics3d/joints.sakura new file mode 100644 index 0000000..745644f --- /dev/null +++ b/physics3d/joints.sakura @@ -0,0 +1,435 @@ +#! Contains joints, which hold two bodies together: a `ball` joint holds them +#! at a point they turn about every way, as a shoulder, within a cone it swings +#! in and how far it twists where it's limited, as a ragdoll's limbs are held; a +#! `hinge` holds them at a point and an axis they turn about alone, as a door, +#! with limits to how far it turns and a motor to turn it; a `fixed` joint holds +#! them as one body, rigidly or springily; a `distance` joint keeps two points +#! apart, rigidly as a rod, within lengths as a rope, or springily; a `slider` +#! lets them slide along an axis, turning together, as a piston; and a +#! `six_dof` joint holds each way they move and turn, along and about its own +#! three axes, locked, limited, or free, as any of the others and more. +#! +#! Joints are solved before contacts in each substep, softly as contacts are: +#! each undoes what has drifted as a stiff, damped spring of the space's joint +#! frequency, and a limit pushes only as far as closes it this substep where +#! it's apart, as a speculative contact does. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics3d; + +#! What a joint holds. +pub enum joint_kind: u8 { + #! The two at a point, about which they turn every way. + ball, + #! The two at a point, about an axis of each, which they turn about alone. + hinge, + #! The two as one. + fixed, + #! Two points apart, as a rod, a rope, or a spring. + distance, + #! The two sliding along an axis, turning together, as a piston. + slider, + #! Each way the two move and turn held as it says. + six_dof, +} + +#! How a six-way joint holds one of the ways its bodies move or turn. +pub enum axis_hold: u8 { + #! Not at all: none of it. + locked, + #! Between its low and its high. + limited, + #! As far as it likes. + free, +} + +#! What a joint is made as: its kind, its bodies, where it holds each, of the +#! body's own places, and what each kind asks. +pub struct joint { + pub var kind := joint_kind::ball; + pub var a: body_id; + pub var b: body_id; + pub var anchor_a: vec3; + pub var anchor_b: vec3; + #! Of a hinge, the axis it turns about, of each body's own directions. + pub var axis_a := vec3::up; + pub var axis_b := vec3::up; + #! Of a hinge, a fixed joint, or a slider, how `b` is turned within `a`'s own + #! turn, where it rests. + pub var reference := quat::identity; + #! Of a slider, a ball joint's limits, or a six-way joint, the joint's own + #! axes as each body is turned, where they rest together: its x is the + #! slider's axis, or the axis a ball joint swings from and twists about. + pub var frame_a := quat::identity; + pub var frame_b := quat::identity; + #! Of a ball joint limited, the widest it swings from its axis, in radians, + #! its twist about it limited from `lower` to `upper`. + pub var cone: f32; + #! Of a six-way joint, how it holds each way: sliding along its frame's x, + #! y, and z, then twisting about x and swinging about y and z, each by + #! `holds`, from `lows` to `highs` where it's limited; and each way not + #! locked driven at `drives`, in lengths or radians a second, by no more + #! than `forces`, of force or torque, none where that's 0. + pub var holds: axis_hold[6]; + pub var lows: f32[6]; + pub var highs: f32[6]; + pub var drives: f32[6]; + pub var forces: f32[6]; + #! Whether the two bodies still meet where their colliders do. + pub var collide: bool; + #! Whether it's limited: a hinge to turning from `lower` to `upper` radians + #! from where it rests, and a distance joint to lengths between them. + pub var limit: bool; + pub var lower: f32; + pub var upper: f32; + #! A motor turning a hinge at a speed, in radians a second, or lengthening a + #! distance joint, in lengths a second, with no more than so much torque or + #! force. + pub var motor: bool; + pub var motor_speed: f32; + pub var max_motor_force: f32; + #! A spring toward a hinge's rest or a distance joint's length, of so many + #! cycles a second, damped so: 1 doesn't spring back. Of a fixed joint, how + #! stiff it holds its place, 0 rigid. + pub var spring: bool; + pub var hertz: f32; + pub var damping: f32 = 1; + #! Of a distance joint, the length it holds. + pub var length: f32 = 1; + #! Of a fixed joint, how stiff it holds its turn, 0 rigid. + pub var angular_hertz: f32; + pub var angular_damping: f32 = 1; + #! A number of its user's. + pub var data: u64; +} + +#! A joint of a space, as `space::join` names it. +pub struct joint_id { + pub var index: u32 = 0xFFFFFFFF; + pub var generation: u32; +} + +pub def joint_id::equals(&this, other: &joint_id): bool { + return this.index == other.index && this.generation == other.generation; +} + +# A joint as the space keeps it, and what a step works out of it. +struct joint_record { + var made: joint; + var generation: u32; + var alive: bool; + var body_a: u32; + var body_b: u32; + var next_a: u32 = 0xFFFFFFFF; + var next_b: u32 = 0xFFFFFFFF; + var slot_a: u32; + var slot_b: u32; + var ma: f32; + var mb: f32; + var ra: vec3; # Each anchor from its body's center, as the step began. + var rb: vec3; + var qa: quat; # Each body's turn as the step began. + var qb: quat; + var delta_center: vec3; + var axial_mass: f32; + var linear: vec3; # Impulses, kept from step to step. + var angular: vec3; + var axial: f32; + var spring_impulse: f32; + var motor_impulse: f32; + var lower_impulse: f32; + var upper_impulse: f32; + var spring_soft: softness; + var linear_soft: softness; + var angular_soft: softness; + var held: f32[24]; # Of a six-way joint, each way's impulses: holding it, at its low, at its high, and driving it. +} + +#! Joins two bodies. +pub def space::join(&mut this, made: joint): joint_id { + return joint_id{} if !this.has(made.a) || !this.has(made.b) || made.a.index == made.b.index; + var index: u32 = 0; + if this.free_joints.length > 0 { + index = this.free_joints[this.free_joints.length - 1]; + this.free_joints.truncate(); + } else { + index = this.joints.length as u32; + this.joints.append(joint_record{}); + } + val generation := this.joints[index as u64].generation + 1; + val a := made.a.index; + val b := made.b.index; + this.joints[index as u64] = joint_record{ + made = made, generation = generation, alive = true, body_a = a, body_b = b, + next_a = this.bodies[a as u64].joints, next_b = this.bodies[b as u64].joints, + }; + this.bodies[a as u64].joints = index; + this.bodies[b as u64].joints = index; + if !made.collide { + this.drop_pairs_between(a, b); + } + this.wake_body(a); + this.wake_body(b); + return joint_id{ index = index, generation = generation }; +} + +#! Holds two bodies at a place of space, about which they turn every way. +pub def space::ball(&mut this, a: body_id, b: body_id, at: vec3): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + return this.join(joint{ kind = joint_kind::ball, a = a, b = b, anchor_a = this.pose_of(a).unapply(at), anchor_b = this.pose_of(b).unapply(at) }); +} + +#! Holds two bodies at a place of space and about an axis through it, of +#! space's directions, as a door's hinge holds it. +pub def space::hinge(&mut this, a: body_id, b: body_id, at: vec3, axis: vec3): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + val pa := this.pose_of(a); + val pb := this.pose_of(b); + val along := axis.normalized(); + return this.join(joint{ + kind = joint_kind::hinge, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at), + axis_a = pa.unrotate(along), axis_b = pb.unrotate(along), reference = (pa.turn.inverse() * pb.turn).normalized(), + }); +} + +# The joint axes, as a body is turned, of a frame whose x is a direction of +# space. +def frame_along(turn: quat, axis: vec3): quat { + val x := axis.normalized(); + val y := perpendicular_to(x); + return (turn.inverse() * quat::of_basis(x, y, x.cross(y))).normalized(); +} + +#! Lets two bodies slide along an axis of space through a place, turning +#! together, as a piston: a slider, its limits, motor, and spring its own to +#! set. +pub def space::slider(&mut this, a: body_id, b: body_id, at: vec3, axis: vec3): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + val pa := this.pose_of(a); + val pb := this.pose_of(b); + return this.join(joint{ + kind = joint_kind::slider, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at), + frame_a = frame_along(pa.turn, axis), frame_b = frame_along(pb.turn, axis), reference = (pa.turn.inverse() * pb.turn).normalized(), + }); +} + +#! Holds two bodies at a place of space, about which they turn, `b` swinging +#! no further than `cone` radians from an axis of space and twisting about it +#! no further than `twist` radians either way, as a shoulder or a hip: a ball +#! joint, limited. +pub def space::cone_twist(&mut this, a: body_id, b: body_id, at: vec3, axis: vec3, cone: f32, twist: f32): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + val pa := this.pose_of(a); + val pb := this.pose_of(b); + return this.join(joint{ + kind = joint_kind::ball, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at), + frame_a = frame_along(pa.turn, axis), frame_b = frame_along(pb.turn, axis), limit = true, cone = cone, lower = -twist, upper = twist, + }); +} + +#! Holds two bodies at a place of space by a six-way joint, its axes those of +#! a rotation of space, each way locked until it's changed, as a fixed joint. +pub def space::six_dof(&mut this, a: body_id, b: body_id, at: vec3, axes: quat = quat::identity): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + val pa := this.pose_of(a); + val pb := this.pose_of(b); + return this.join(joint{ + kind = joint_kind::six_dof, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at), + frame_a = (pa.turn.inverse() * axes).normalized(), frame_b = (pb.turn.inverse() * axes).normalized(), + }); +} + +#! Holds two bodies together as one, about a place of space. +pub def space::fix(&mut this, a: body_id, b: body_id, at: vec3): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + val pa := this.pose_of(a); + val pb := this.pose_of(b); + return this.join(joint{ + kind = joint_kind::fixed, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at), + reference = (pa.turn.inverse() * pb.turn).normalized(), + }); +} + +#! Keeps two places of space, one of each body, as far apart as they are. +pub def space::tie(&mut this, a: body_id, b: body_id, at_a: vec3, at_b: vec3): joint_id { + return joint_id{} if !this.has(a) || !this.has(b); + return this.join(joint{ + kind = joint_kind::distance, a = a, b = b, anchor_a = this.pose_of(a).unapply(at_a), anchor_b = this.pose_of(b).unapply(at_b), + length = (at_b - at_a).length, collide = true, + }); +} + +#! Whether a joint is of it still. +pub def space::has(&this, id: joint_id): bool { + return id.index < this.joints.length as u32 && this.joints[id.index as u64].alive && this.joints[id.index as u64].generation == id.generation; +} + +#! What a joint was made as, or last changed to. +pub def space::joint_of(&this, id: joint_id): &joint { + return &this.joints[id.index as u64].made; +} + +#! Changes what a joint asks, as its motor or limits, keeping its bodies, and +#! wakes them. What it no longer asks pushes no more: a motor, limits, or a +#! spring turned off, and a six-way joint's ways held otherwise. +pub def space::change(&mut this, id: joint_id, made: joint): void { + return if !this.has(id); + val j := id.index as u64; + var r := this.joints[j]; + val a := r.made.a; + val b := r.made.b; + if !made.motor { + r.motor_impulse = 0; + } + if !made.limit { + r.lower_impulse = 0; + r.upper_impulse = 0; + } + if !made.spring { + r.spring_impulse = 0; + } + for k in 0..6u { + if made.holds[k] != r.made.holds[k] || made.kind != r.made.kind || made.limit != r.made.limit { + r.held = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + r.linear = vec3::zero; + } + if made.forces[k] == 0 { + r.held[18 + k] = 0; + } + } + r.made = made; + r.made.a = a; + r.made.b = b; + this.joints[j] = r; + this.wake_body(a.index); + this.wake_body(b.index); +} + +#! How far a hinge is turned from where it rests, in radians, about its axis. +pub def space::angle_of(&this, id: joint_id): f32 { + return 0 if !this.has(id); + val j := &this.joints[id.index as u64]; + return hinge_angle(&j.made, this.bodies[j.body_a as u64].at.turn, this.bodies[j.body_b as u64].at.turn); +} + +# How far `b` is turned about a hinge's axis from where it rests, within `a`'s +# own turn: the twist of the turn between them. +def hinge_angle(made: &joint, qa: quat, qb: quat): f32 { + val apart := (made.reference.inverse() * (qa.inverse() * qb)).normalized(); + val axis := made.axis_a; + val along := apart.x * axis.x + apart.y * axis.y + apart.z * axis.z; + return unwound(2 * math::atan2(along, apart.w)); +} + +# An angle brought within -π to π. +def unwound(angle: f32): f32 { + val pi := math::pi as f32; + return angle < -pi ? angle + 2 * pi : angle > pi ? angle - 2 * pi : angle; +} + +#! Takes a joint away, waking its bodies. +pub def space::unjoin(&mut this, id: joint_id): void { + return if !this.has(id); + this.drop_joint(id.index); +} + +def space::drop_joint(&mut this, j: u32): void { + val a := this.joints[j as u64].body_a; + val b := this.joints[j as u64].body_b; + this.unlink_joint(j, a); + this.unlink_joint(j, b); + this.joints[j as u64].alive = false; + this.free_joints.append(j); + this.wake_body(a); + this.wake_body(b); + this.touch_colliders(a); +} + +def space::unlink_joint(&mut this, j: u32, body: u32): void { + val next := this.next_joint(j, body); + if this.bodies[body as u64].joints == j { + this.bodies[body as u64].joints = next; + return; + } + var k := this.bodies[body as u64].joints; + while k != none { + val after := this.next_joint(k, body); + if after == j { + if this.joints[k as u64].body_a == body { + this.joints[k as u64].next_a = next; + } else { + this.joints[k as u64].next_b = next; + } + return; + } + k = after; + } +} + +def space::next_joint(&this, j: u32, body: u32): u32 { + return this.joints[j as u64].body_a == body ? this.joints[j as u64].next_a : this.joints[j as u64].next_b; +} + +# Whether a joint holds two bodies and keeps them from meeting. +def space::joined_apart(&this, a: u32, b: u32): bool { + var j := this.bodies[a as u64].joints; + while j != none { + val joint := &this.joints[j as u64]; + val other := joint.body_a == a ? joint.body_b : joint.body_a; + return true if other == b && !joint.made.collide; + j = this.next_joint(j, a); + } + return false; +} + +def space::drop_joints_of(&mut this, b: u32): void { + while this.bodies[b as u64].joints != none { + this.drop_joint(this.bodies[b as u64].joints); + } +} + +def space::drop_pairs_between(&mut this, a: u32, b: u32): void { + for p in 0..this.pairs.length { + continue if !this.pairs[p].alive; + val ba := this.colliders[this.pairs[p].a as u64].body; + val bb := this.colliders[this.pairs[p].b as u64].body; + if (ba == a && bb == b) || (ba == b && bb == a) { + this.drop_pair(p as u32, false); + } + } +} + +def space::touch_colliders(&mut this, b: u32): void { + var c := this.bodies[b as u64].colliders; + while c != none { + if !this.colliders[c as u64].moved { + this.colliders[c as u64].moved = true; + this.moved.append(c); + } + c = this.colliders[c as u64].next; + } +} + +def space::join_jointed(&this, parent: &mut vector): void { + for j in 0..this.joints.length { + val joint := &this.joints[j]; + continue if !joint.alive; + if parent[joint.body_a as u64] != none && parent[joint.body_b as u64] != none { + join(parent, joint.body_a, joint.body_b); + } + } +} + +#! Visits each joint, as `visit(joint, at_a, at_b)`, where it holds each of its +#! bodies, of space's places, until it gives false, as gizmos draw them. +pub def space::each_joint(&this, visit: F): void where F: invokable { + for j in 0..this.joints.length { + val r := &this.joints[j]; + continue if !r.alive; + val at_a := this.bodies[r.body_a as u64].at.apply(r.made.anchor_a); + val at_b := this.bodies[r.body_b as u64].at.apply(r.made.anchor_b); + return if !visit(joint_id{ index = j as u32, generation = r.generation }, at_a, at_b); + } +} \ No newline at end of file diff --git a/physics3d/mass.sakura b/physics3d/mass.sakura new file mode 100644 index 0000000..b71b041 --- /dev/null +++ b/physics3d/mass.sakura @@ -0,0 +1,116 @@ +#! Contains `mass_data`: how heavy a shape is of a density, where its mass is +#! centered, and how hard it is to turn about each axis, its inertia tensor, +#! as a body's colliders sum to it. + +import std::math; +import malunal::linear; +module malunal::physics3d; + +#! How heavy something is, where its mass is centered, of its body's own +#! places, and its inertia tensor about that center, of the body's own axes. +pub struct mass_data { + pub var mass: f32; + pub var center: vec3; + pub var inertia: mat3; +} + +#! It and another together: their masses summed about their joint center. +pub def mass_data::add(&this, other: &mass_data): mass_data { + val mass := this.mass + other.mass; + return mass_data{ inertia = this.inertia + other.inertia } if mass <= 0; + val center := (this.center * this.mass + other.center * other.mass) * (1 / mass); + val inertia := this.inertia + shifted(this.mass, this.center - center) + other.inertia + shifted(other.mass, other.center - center); + return mass_data{ mass = mass, center = center, inertia = inertia }; +} + +# What a mass adds to an inertia tensor, turning about a center as far off as +# `d`, as the parallel axis theorem finds. +def shifted(mass: f32, d: vec3): mat3 { + val dd := d.dot(d); + return mat3{ + vec3{ mass * (dd - d.x * d.x), -mass * d.x * d.y, -mass * d.x * d.z }, + vec3{ -mass * d.y * d.x, mass * (dd - d.y * d.y), -mass * d.y * d.z }, + vec3{ -mass * d.z * d.x, -mass * d.z * d.y, mass * (dd - d.z * d.z) }, + }; +} + +# A tensor of `across` about every axis but `along` about the axis `u`. +def about_axis(across: f32, along: f32, u: vec3): mat3 { + val k := along - across; + return mat3{ + vec3{ across + k * u.x * u.x, k * u.x * u.y, k * u.x * u.z }, + vec3{ k * u.y * u.x, across + k * u.y * u.y, k * u.y * u.z }, + vec3{ k * u.z * u.x, k * u.z * u.y, across + k * u.z * u.z }, + }; +} + +#! Its mass of a density, a mass for each volume of 1. +pub def shape::mass(&this, density: f32): mass_data { + val pi := math::pi as f32; + val r := this.radius; + if this.kind == shape_kind::sphere { + val mass := density * 4f / 3f * pi * r * r * r; + val i := 0.4 * mass * r * r; + return mass_data{ mass = mass, center = this.a, inertia = about_axis(i, i, vec3::up) }; + } + if this.kind == shape_kind::capsule { + # A cylinder between its ends, and a sphere of its two round halves, each + # half's own center 3r/8 past the cylinder's end. + val length := (this.b - this.a).length; + val cylinder := density * pi * r * r * length; + val ball := density * 4f / 3f * pi * r * r * r; + val along := cylinder * r * r * 0.5 + ball * 0.4 * r * r; + val across := cylinder * (length * length / 12 + r * r / 4) + ball * (0.4 * r * r + length * length / 4 + 3 * length * r / 8); + return mass_data{ mass = cylinder + ball, center = (this.a + this.b) * 0.5, inertia = about_axis(across, along, (this.b - this.a).normalized()) }; + } + return hull_mass(this.as_hull(), density); +} + +# A hull's, as the tetrahedra of each face's triangles and a place within it +# sum it. +def hull_mass(h: &hull, density: f32): mass_data { + val origin := h.center; + var volume: f32 = 0; + var center := vec3::zero; + # The covariance of the hull's places about the origin. + var xx: f32 = 0; + var yy: f32 = 0; + var zz: f32 = 0; + var xy: f32 = 0; + var xz: f32 = 0; + var yz: f32 = 0; + for f in 0..h.faces { + val a := h.point(h.corner(f, 0)) - origin; + for k in 1..h.face_size(f) - 1 { + val b := h.point(h.corner(f, k)) - origin; + val c := h.point(h.corner(f, k + 1)) - origin; + val det := a.dot(b.cross(c)); + volume += det / 6; + center = center + (a + b + c) * (det / 24); + val s := a + b + c; + val w := det / 120; + xx += w * (a.x * a.x + b.x * b.x + c.x * c.x + s.x * s.x); + yy += w * (a.y * a.y + b.y * b.y + c.y * c.y + s.y * s.y); + zz += w * (a.z * a.z + b.z * b.z + c.z * c.z + s.z * s.z); + xy += w * (a.x * a.y + b.x * b.y + c.x * c.y + s.x * s.y); + xz += w * (a.x * a.z + b.x * b.z + c.x * c.z + s.x * s.z); + yz += w * (a.y * a.z + b.y * b.z + c.y * c.z + s.y * s.z); + } + } + return mass_data{} if volume <= tiny; + center = center * (1 / volume); + val mass := density * volume; + # Of the covariance about the center of mass, the tensor. + xx = density * xx - mass * center.x * center.x; + yy = density * yy - mass * center.y * center.y; + zz = density * zz - mass * center.z * center.z; + xy = density * xy - mass * center.x * center.y; + xz = density * xz - mass * center.x * center.z; + yz = density * yz - mass * center.y * center.z; + val inertia := mat3{ + vec3{ yy + zz, -xy, -xz }, + vec3{ -xy, xx + zz, -yz }, + vec3{ -xz, -yz, xx + yy }, + }; + return mass_data{ mass = mass, center = origin + center, inertia = inertia }; +} diff --git a/physics3d/mesh.sakura b/physics3d/mesh.sakura new file mode 100644 index 0000000..39a8d25 --- /dev/null +++ b/physics3d/mesh.sakura @@ -0,0 +1,318 @@ +#! Contains `triangle_mesh`, the triangles of a surface, as a level's ground and +#! walls are: kept in a tree of their boxes, and met a triangle at a time by +#! shapes and rays. +#! +#! A shape meeting a triangle by an edge or a corner is pushed out as the +#! triangle's face pushes it, where that edge is one two triangles share flat, +#! or hollow, as a floor's seams and a room's corners are, as Jolt's active +#! edges keep: so a body slides along a floor of many triangles as along one, +#! never caught on the seams between them. An edge two triangles share at a +#! ridge, turning more than 5 degrees, and an edge of one triangle alone, push +#! as they meet. + +import std::containers; +import std::math; +import malunal::geometry; +import malunal::linear; +module malunal::physics3d; + +# Two triangles sharing an edge turning less than this, the cosine of 5 +# degrees, are as one. +const ridge: f32 = 0.9962; + +#! The triangles of a surface, of places of its own, as a pose places it. +pub struct triangle_mesh { + var _points: vector; + var _indices: vector; + var _normals: vector; + var _active: vector; # Of each triangle, bit `k` where edge `k`, from corner `k` to the next, pushes as it meets. + var _tree: aabb_tree; + var _field: heightfield; # Its triangles, where they're a heightfield's. + var _heights: bool; +} + +#! Where a ray met a mesh: how far along it, where, which way the triangle it +#! met faces, toward the ray's beginning, and which triangle. +pub struct mesh_hit { + pub var distance: f32; + pub var point: vec3; + pub var normal: vec3; + pub var triangle: u32; +} + +# An edge, and the triangles using it, each as its index times 3 and the +# edge's place in it. +struct edge_use { + var first: u64; + var second: u64; + var count: u32; +} + +#! The mesh of places and triangles of them, three indices each, +#! counterclockwise as their front is seen: those of no area, or of an index +#! past the places, left out. +pub def triangle_mesh::new(points: span, indices: span): triangle_mesh { + var made := triangle_mesh{ + _points = vector::::new(), _indices = vector::::new(), _normals = vector::::new(), + _active = vector::::new(), _tree = aabb_tree::new(0), + }; + made._points.extend(points); + var t: u64 = 0; + while t + 2 < indices.length { + val a := indices[t]; + val b := indices[t + 1]; + val c := indices[t + 2]; + t += 3; + continue if a as u64 >= points.length || b as u64 >= points.length || c as u64 >= points.length; + val facing := (points[b as u64] - points[a as u64]).cross(points[c as u64] - points[a as u64]); + continue if facing.length_squared <= tiny * tiny; + made._indices.append(a); + made._indices.append(b); + made._indices.append(c); + made._normals.append(facing.normalized()); + made._active.append(7); + } + made.find_edges(); + for i in 0..made._normals.length { + val c := made.triangle(i as u32); + _ = made._tree.insert(bounds{ c[0].min(c[1]).min(c[2]), c[0].max(c[1]).max(c[2]) }, i); + } + return made; +} + +# The triangles of a heightfield, made as they're met. +def triangle_mesh::of_field(field: heightfield): triangle_mesh { + var made := triangle_mesh::new(span::::blank(), span::::blank()); + made._field = move(field); + made._heights = true; + return made; +} + +# Finds which edges push as they meet: those two triangles share, turning +# less than 5 degrees or hollow, don't. +def triangle_mesh::find_edges(&mut this): void { + var uses := vector::::new(); + var found := dict::::new(); + for t in 0..this._normals.length { + for k in 0..3u { + val from := this._indices[t * 3 + k]; + val to := this._indices[t * 3 + (k + 1) % 3]; + val key := ((math::min(from, to) as u64) << 32) | math::max(from, to) as u64; + if found.get(&key) is some(&at) { + val index: u64 = at; + if uses[index].count == 1 { + uses[index].second = t * 3 + k; + } + uses[index].count++; + } else { + found.set(key, uses.length); + uses.append(edge_use{ first = t * 3 + k, count = 1 }); + } + } + } + for i in 0..uses.length { + continue if uses[i].count != 2; + val t1 := uses[i].first / 3; + val k1 := uses[i].first % 3; + val t2 := uses[i].second / 3; + val k2 := uses[i].second % 3; + val n1 := this._normals[t1]; + val n2 := this._normals[t2]; + # The corner of the second triangle off the edge, below the first's plane + # where the edge is a ridge. + val off := this._points[this._indices[t2 * 3 + (k2 + 2) % 3] as u64]; + val on := this._points[this._indices[t1 * 3 + k1] as u64]; + val ridged := n1.dot(off - on) < 0 && n1.dot(n2) < ridge; + continue if ridged; + this._active[t1] = without_bit(this._active[t1], k1); + this._active[t2] = without_bit(this._active[t2], k2); + } +} + +# Bits of three edges, but one. +def without_bit(bits: u8, k: u64): u8 { + val bit: u32 = 1; + return ((bits as u32) & (7 - (bit << k as u32))) as u8; +} + +#! How many triangles it has. +pub val triangle_mesh::length: u64 { + get => this._heights ? this._field.length : this._normals.length; +} + +#! A triangle's corners. +pub def triangle_mesh::triangle(&this, t: u32): vec3[3] { + return this._field.triangle(t) if this._heights; + val at := t as u64 * 3; + return [ + this._points[this._indices[at] as u64], this._points[this._indices[at + 1] as u64], this._points[this._indices[at + 2] as u64], + ]; +} + +#! The way a triangle's front faces. +pub def triangle_mesh::normal(&this, t: u32): vec3 { + return this._field.normal(t) if this._heights; + return this._normals[t as u64]; +} + +# Which of a triangle's edges push as they meet, a bit each. +def triangle_mesh::active_bits(&this, t: u32): u8 { + return this._field.active(t) if this._heights; + return this._active[t as u64]; +} + +#! Whether a triangle's edge `k`, from its corner `k` to the next, pushes as it +#! meets a shape, rather than as the triangle's face. +pub def triangle_mesh::is_active(&this, t: u32, k: u32): bool { + return has_bit(this.active_bits(t), k); +} + +def has_bit(bits: u8, k: u32): bool { + return (((bits as u32) >> k) & 1) != 0; +} + +#! The box holding it, of its own places. +pub def triangle_mesh::bounds(&this): bounds { + return this._field.bounds if this._heights; + var made := bounds::blank; + for i in 0..this._points.length { + made = made.including(this._points[i]); + } + return made; +} + +#! Visits the manifold of a shape against each triangle it meets, as +#! `visit(triangle, m)`, until it gives false: `at` places the mesh, and `at_s` +#! the shape, and each manifold's normal is from the triangle toward the shape, +#! in space. Within a `margin`, as `collide` gives them, triangles apart are +#! visited too. +pub def triangle_mesh::collide(&this, at: pose, s: &shape, at_s: pose, margin: f32, visit: F): void + where F: invokable { + val local := at.unapply_pose(at_s); + this.triangles_in(grown(s.bounds(local), margin), def(t: u32): bool { + val c := this.triangle(t); + val face := shape::of_hull(hull::triangle(c[0], c[1], c[2])); + val found := collide(&face, pose::identity, s, local, margin) else { return true; }; + return visit(t, placed(face_pushed(&c, this.normal(t), this.active_bits(t), found, s.radius), &at)); + }); +} + +#! Visits each triangle whose box a box of its own places meets, as +#! `visit(triangle)`, until it gives false. +pub def triangle_mesh::triangles_in(&this, box: bounds, visit: F): void where F: invokable { + if this._heights { + this._field.triangles_in(box, visit); + return; + } + this._tree.query(box, def(leaf: u32, data: u64): bool { + return visit(data as u32); + }); +} + +#! Whether a shape meets any triangle, `at` placing the mesh and `at_s` the +#! shape. +pub def triangle_mesh::overlaps(&this, at: pose, s: &shape, at_s: pose): bool { + var met := false; + this.collide(at, s, at_s, 0, def(t: u32, m: manifold): bool { + met = true; + return false; + }); + return met; +} + +# A manifold of a triangle, as its face pushes where it met an edge, or a +# corner, of the triangle that doesn't push: its normal the face's, and each +# point as deep below the face's plane as the shape is there, of a radius +# around its core. +def face_pushed(c: &vec3[3], n: vec3, active: u8, met: manifold, radius: f32): manifold { + val along := met.normal.dot(n); + return met if math::abs(along) > 0.9998 || active == 7; + var deepest: u32 = 0; + for i in 1..met.count { + if met.points[i].depth > met.points[deepest].depth { + deepest = i; + } + } + # Where the deepest point is on the triangle: half its depth along the + # normal from midway. + val on := met.points[deepest].point + met.normal * (met.points[deepest].depth * 0.5); + val region := region_of(on, c[0], c[1], c[2]); + # Within the face, or by a corner or edge that pushes, it pushes as it met. + return met if region == 6; + if region >= 3 { + return met if has_bit(active, region - 3); + } else if has_bit(active, region) || has_bit(active, (region + 2) % 3) { + return met; + } + # Each point's place on the shape's surface, half its depth back along the + # normal, and its core within; then the shape's deepest there along the + # face's normal. + val facing := along >= 0 ? n : -n; + var made := met; + made.normal = facing; + for i in 0..met.count { + val surface := met.points[i].point - met.normal * (met.points[i].depth * 0.5); + val deepest := surface + met.normal * radius - facing * radius; + val depth := facing.dot(c[0] - deepest); + made.points[i].point = deepest + facing * (depth * 0.5); + made.points[i].depth = depth; + } + return made; +} + +# Which part of a triangle a place on it is on, within a ten-thousandth of +# its longest edge: a corner, 0 to 2; an edge, 3 to 5, of edge `k` from corner +# `k` to the next; or within its face, 6. +def region_of(p: vec3, a: vec3, b: vec3, c: vec3): u32 { + val corners: vec3[3] = [a, b, c]; + val longest := math::max((b - a).length, math::max((c - b).length, (a - c).length)); + val near := longest * 1e-4 + tiny; + for k in 0..3u { + return k as u32 if (p - corners[k]).length <= near; + } + for k in 0..3u { + return (3 + k) as u32 if (p - nearest_on_segment(p, corners[k], corners[(k + 1) % 3])).length <= near; + } + return 6; +} + +#! Where a ray first meets a triangle, `at` placing the mesh: from a place, +#! along a direction of length 1, as far as `reach`, from either side. +pub def triangle_mesh::ray_cast(&this, at: pose, origin: vec3, direction: vec3, reach: f32): maybe { + val o := at.unapply(origin); + val d := at.unrotate(direction); + if this._heights { + val found := this._field.ray_cast(o, d, reach) else { return nothing{}; }; + return mesh_hit{ distance = found.distance, point = at.apply(found.point), normal = at.rotate(found.normal), triangle = found.triangle }; + } + var best: maybe = nothing{}; + this._tree.ray_cast(o, d, reach, def(leaf: u32, data: u64, so_far: f32): f32 { + val c := this.triangle(data as u32); + val t := ray_triangle(o, d, c[0], c[1], c[2]) else { return so_far; }; + return so_far if t > so_far; + val n := this._normals[data]; + best = mesh_hit{ distance = t, point = at.apply(o + d * t), normal = at.rotate(n.dot(d) <= 0 ? n : -n), triangle = data as u32 }; + return math::max(t, tiny); + }); + return best; +} + +# How far along a ray it meets a triangle, from either side, as Möller and +# Trumbore find it. +def ray_triangle(o: vec3, d: vec3, a: vec3, b: vec3, c: vec3): maybe { + val e1 := b - a; + val e2 := c - a; + val p := d.cross(e2); + val det := e1.dot(p); + return nothing{} if math::abs(det) < 1e-12; + val inverse := 1 / det; + val s := o - a; + val u := s.dot(p) * inverse; + return nothing{} if u < 0 || u > 1; + val q := s.cross(e1); + val v := d.dot(q) * inverse; + return nothing{} if v < 0 || u + v > 1; + val t := e2.dot(q) * inverse; + return nothing{} if t < 0; + return t; +} diff --git a/physics3d/physics3d.sakura b/physics3d/physics3d.sakura new file mode 100644 index 0000000..a4c207d --- /dev/null +++ b/physics3d/physics3d.sakura @@ -0,0 +1,85 @@ +#! Contains `physics3d`: what collides and moves in space, as a game of three +#! dimensions asks it. Shapes, spheres, capsules, and convex hulls, boxes among +#! them, each about the origin of its body and placed by a `pose`; whether two +#! meet, and the `manifold` of where and how deep, which way to push them +#! apart; where a ray first meets one; an `aabb_tree` of many, which finds those +#! near a box or along a ray without passing over the rest; and a +#! `triangle_mesh`, as a level's ground and walls are, met a triangle at a +#! time, but for the edges two triangles share flat or hollow, so a body slides +#! along a floor of many triangles as along one. +#! +#! And a `space` of bodies, as `physics2d`'s in a plane: each made of +#! colliders, of shapes, a triangle mesh, or a heightfield, pulled by gravity, +#! pushed by forces and by what it meets, held to others by joints, and stepped +#! forward in time as Box2D's soft step solves it, its contacts as lanes of +#! eight, on as many threads as it's given, swept where it moves fast, and +#! sleeping where it and all it rests on are still; asked of what overlaps and +#! what casts meet; and walking `character`s. +#! +#! Space is `linear`'s: right-handed, y up, and rotations as quaternions. A +#! hull's faces are counterclockwise as they're seen from outside, each normal +#! facing out. A shape's surface is within it, so two shapes touching meet, at a +#! depth of 0. + +import std::math; +import malunal::linear; +module malunal::physics3d; + +# How near two numbers are taken as one, as lengths in a game's units are. +const tiny: f32 = 1e-6; + +# How far a feature may be past another and still be taken as as good, so the +# same pair gives the same face from one frame to the next. +const tolerance: f32 = 1e-3; + +# The point of a segment nearest a place. +def nearest_on_segment(p: vec3, a: vec3, b: vec3): vec3 { + val e := b - a; + val length_squared := e.dot(e); + return a if length_squared <= tiny * tiny; + val t := math::clamp((p - a).dot(e) / length_squared, 0f, 1f); + return a + e * t; +} + +# The points of two segments nearest one another: on `a1`-`a2` first, then on +# `b1`-`b2`, as Ericson's Real-Time Collision Detection finds them. +def nearest_of_segments(a1: vec3, a2: vec3, b1: vec3, b2: vec3): vec3[2] { + val d1 := a2 - a1; + val d2 := b2 - b1; + val r := a1 - b1; + val a := d1.dot(d1); + val e := d2.dot(d2); + val f := d2.dot(r); + var s: f32 = 0; + var t: f32 = 0; + if a <= tiny && e <= tiny { + return [a1, b1]; + } + if a <= tiny { + t = math::clamp(f / e, 0f, 1f); + } else { + val c := d1.dot(r); + if e <= tiny { + s = math::clamp(-c / a, 0f, 1f); + } else { + val b := d1.dot(d2); + val denominator := a * e - b * b; + s = denominator > tiny ? math::clamp((b * f - c * e) / denominator, 0f, 1f) : 0; + t = (b * s + f) / e; + if t < 0 { + t = 0; + s = math::clamp(-c / a, 0f, 1f); + } else if t > 1 { + t = 1; + s = math::clamp((b - c) / a, 0f, 1f); + } + } + } + return [a1 + d1 * s, b1 + d2 * t]; +} + +# A direction at right angles to another, of length 1. +def perpendicular_to(v: vec3): vec3 { + val other := math::abs(v.x) < 0.57 ? vec3::right : vec3::up; + return v.cross(other).normalized(); +} diff --git a/physics3d/pose.sakura b/physics3d/pose.sakura new file mode 100644 index 0000000..5e10009 --- /dev/null +++ b/physics3d/pose.sakura @@ -0,0 +1,65 @@ +#! Contains `pose`, where a body is in space and which way it's turned, which +#! places its shapes. + +import std::serial; +import malunal::linear; +module malunal::physics3d; + +#! Where a body is in space, and which way it's turned: what a place of its own, +#! as its shapes' corners are, is in space. +@serial +pub struct pose { + @serial pub var at: vec3; + @serial pub var turn := quat::identity; +} + +#! At the origin, unturned. +pub val pose::identity := pose{}; + +#! A pose at a place, turned by a rotation. +pub def pose::of(at: vec3, turn: quat = quat::identity): pose { + return pose{ at = at, turn = turn }; +} + +pub def pose::equals(&this, other: &pose): bool { + return this.at == other.at && this.turn == other.turn; +} + +#! Where a place of the body's own is in space. +pub def pose::apply(&this, local: vec3): vec3 { + return this.at + this.turn * local; +} + +#! Where a place of space is in the body's own. +pub def pose::unapply(&this, place: vec3): vec3 { + return this.turn.inverse() * (place - this.at); +} + +#! A direction of the body's own, turned as it's turned. +pub def pose::rotate(&this, direction: vec3): vec3 { + return this.turn * direction; +} + +#! A direction of space, as the body's own. +pub def pose::unrotate(&this, direction: vec3): vec3 { + return this.turn.inverse() * direction; +} + +#! It after another: the pose of what's placed by `other` within what this +#! places. +pub def pose::mul(&this, other: &pose): pose { + return pose{ at = this.apply(other.at), turn = (this.turn * other.turn).normalized() }; +} + +#! The pose undoing it: a place it puts somewhere, put back. +pub def pose::inverse(&this): pose { + val back := this.turn.inverse(); + return pose{ at = back * -this.at, turn = back }; +} + +#! Another pose of space, as one within what this places, of its own places: +#! what `this * found` is `other` of. +pub def pose::unapply_pose(&this, other: pose): pose { + val back := this.turn.inverse(); + return pose{ at = back * (other.at - this.at), turn = (back * other.turn).normalized() }; +} diff --git a/physics3d/queries.sakura b/physics3d/queries.sakura new file mode 100644 index 0000000..7eb683f --- /dev/null +++ b/physics3d/queries.sakura @@ -0,0 +1,117 @@ +#! Contains what a space is asked of the shapes in it: which colliders a shape +#! overlaps, and where a shape cast along a motion first meets one, as a +#! character's feet and a thrown stone ask. + +import std::containers; +import std::math; +import malunal::geometry; +import malunal::linear; +module malunal::physics3d; + +#! Where a shape cast through a space first met one of its colliders: which, +#! of which body, how far along the motion, as a fraction of it, where on what +#! it met, which way that faces, toward the shape cast, and of a mesh's or a +#! heightfield's, which triangle. +pub struct space_cast { + pub var collider: collider_id; + pub var body: body_id; + pub var fraction: f32; + pub var point: vec3; + pub var normal: vec3; + pub var triangle: u32 = 0xFFFFFFFF; +} + +#! What a query of a space passes over: colliders on no layer of its `mask`; +#! sensors, unless `sensors`; and those whose data is `ignore`, where it isn't +#! 0, as the asker's own, a body and its colliders given an entity's bits. +pub struct query_filter { + pub var mask: u32 = 0xFFFFFFFF; + pub var sensors := false; + pub var ignore: u64 = 0; +} + +# Whether a query of a filter asks of a collider. +def space::passes(&this, c: u32, filter: &query_filter): bool { + val held := &this.colliders[c as u64].made; + return (held.layers & filter.mask) != 0 && (!held.sensor || filter.sensors) && (filter.ignore == 0 || held.data != filter.ignore); +} + +def space::named(&this, c: u32): collider_id { + return collider_id{ index = c, generation = this.colliders[c as u64].generation }; +} + +def space::body_named(&this, b: u32): body_id { + return body_id{ index = b, generation = this.bodies[b as u64].generation }; +} + +#! Visits each collider on a layer of a mask that a shape overlaps, where a +#! pose places it, sensors passed over, as `visit(collider, body)`, until it +#! gives false. +pub def space::overlap(&this, s: &shape, at: pose, mask: u32, visit: F): void where F: invokable { + this.overlap(s, at, query_filter{ mask = mask }, visit); +} + +#! Visits each collider a shape overlaps, where a pose places it, that a +#! filter asks of, as `visit(collider, body)`, until it gives false. +pub def space::overlap(&this, s: &shape, at: pose, filter: query_filter, visit: F): void where F: invokable { + this.tree.query(s.bounds(at), def(leaf: u32, data: u64): bool { + val c := data as u32; + return true if !this.passes(c, &filter); + val held := &this.colliders[data]; + val placed := this.bodies[held.body as u64].at; + var met := false; + if held.is_mesh() { + met = this.meshes[held.mesh as u64].overlaps(placed, s, at); + } else { + met = overlaps(&held.made.shape, placed, s, at); + } + return true if !met; + return visit(this.named(c), this.body_named(held.body)); + }); +} + +#! Where a shape, cast along a motion of space from where a pose places it, +#! first meets a collider on a layer of a mask, sensors passed over: within a +#! quarter of the slop of what it meets, a little short of touching. A +#! fraction of 0 where it overlaps something as it begins. Colliders of +#! `except`, a body of its own, as a character's, are passed over. +pub def space::shape_cast(&this, s: &shape, at: pose, motion: vec3, mask: u32 = 0xFFFFFFFF, except: body_id = body_id{}): maybe { + return this.shape_cast(s, at, motion, query_filter{ mask = mask }, except); +} + +#! Where a shape, cast along a motion as `shape_cast` casts it, first meets a +#! collider a filter asks of. +pub def space::shape_cast(&this, s: &shape, at: pose, motion: vec3, filter: query_filter, except: body_id = body_id{}): maybe { + var best: maybe = nothing{}; + var first: f32 = 2; + val tolerance := 0.25 * this.slop; + val moved := pose{ at = at.at + motion, turn = at.turn }; + val box := s.bounds(at).merged(s.bounds(moved)); + this.tree.query(box, def(leaf: u32, data: u64): bool { + val c := data as u32; + return true if !this.passes(c, &filter) || this.colliders[data].body == except.index; + val held := &this.colliders[data]; + val placed := this.bodies[held.body as u64].at; + if held.is_mesh() { + val surface := &this.meshes[held.mesh as u64]; + surface.triangles_in(local_box(box, placed), def(t: u32): bool { + val corners := surface.triangle(t); + val face := shape::of_hull(hull::triangle(corners[0], corners[1], corners[2])); + val hit := shape_cast(&face, placed, s, at, motion, tolerance) else { return true; }; + if hit.fraction < first { + first = hit.fraction; + best = space_cast{ collider = this.named(c), body = this.body_named(held.body), fraction = hit.fraction, point = hit.point, normal = hit.normal, triangle = t }; + } + return true; + }); + return true; + } + val hit := shape_cast(&held.made.shape, placed, s, at, motion, tolerance) else { return true; }; + if hit.fraction < first { + first = hit.fraction; + best = space_cast{ collider = this.named(c), body = this.body_named(held.body), fraction = hit.fraction, point = hit.point, normal = hit.normal }; + } + return true; + }); + return best; +} diff --git a/physics3d/shape.sakura b/physics3d/shape.sakura new file mode 100644 index 0000000..05ee063 --- /dev/null +++ b/physics3d/shape.sakura @@ -0,0 +1,246 @@ +#! Contains `shape`: a sphere, a capsule, or a convex hull, about the origin of +#! its body; the box holding it where a pose places it; whether it holds a +#! place; and where a ray first meets it. + +import std::math; +import malunal::geometry; +import malunal::linear; +module malunal::physics3d; + +#! What a shape is. +pub enum shape_kind: u8 { + #! The places within its radius of its middle. + sphere, + #! The places within its radius of a segment, between its two ends, as a + #! pill. + capsule, + #! A convex polyhedron, as a box. + hull, +} + +#! A shape of a body, about the body's origin, as a pose places it: a sphere, +#! a capsule, or a convex hull. A sphere is its middle and a radius around it, +#! a capsule its two ends and a radius around the segment between them, and a +#! hull its corners and faces. +pub struct shape { + var _kind: shape_kind; + var _radius: f32; + var _a: vec3; + var _b: vec3; + var _hull: hull; +} + +#! Where a ray met a shape: how far along it, where, and which way the shape +#! faces there. +pub struct ray_hit { + pub var distance: f32; + pub var point: vec3; + pub var normal: vec3; +} + +#! A sphere of a radius, about a middle, the body's origin at first. +pub def shape::sphere(radius: f32, center: vec3 = vec3::zero): shape { + return shape{ _kind = shape_kind::sphere, _radius = radius, _a = center, _b = center }; +} + +#! A capsule of a radius about the segment between two places: a sphere of the +#! radius, where they're one place. +pub def shape::capsule(a: vec3, b: vec3, radius: f32): shape { + return shape::sphere(radius, a) if (b - a).length_squared <= tiny * tiny; + return shape{ _kind = shape_kind::capsule, _radius = radius, _a = a, _b = b }; +} + +#! A capsule standing up, along y, as a character's body: so wide and so high +#! in all, its ends round, about a middle. Narrower than it's high, or a +#! sphere. +pub def shape::pill(width: f32, height: f32, center: vec3 = vec3::zero): shape { + val radius := width / 2; + val reach := math::max(height / 2 - radius, 0f); + return shape::capsule(center - vec3{ 0, reach, 0 }, center + vec3{ 0, reach, 0 }, radius); +} + +#! A box reaching so far each way from its middle, about a place, turned by a +#! rotation. +pub def shape::box(half: vec3, center: vec3 = vec3::zero, turn: quat = quat::identity): shape { + return shape::of_hull(hull::box(half, center, turn)); +} + +#! The convex hull around places, as `hull::of` makes it: nothing where they +#! hold no volume, or their hull has too many corners. +pub def shape::hull_of(places: span): maybe { + if hull::of(places) is some(made) { + return shape::of_hull(made); + } + return nothing{}; +} + +#! A shape of a hull. +pub def shape::of_hull(h: hull): shape { + return shape{ _kind = shape_kind::hull, _a = h.center, _b = h.center, _hull = h }; +} + +pub val shape::kind: shape_kind { + get => this._kind; +} + +#! How far around its middle or segment it reaches: a sphere's or a capsule's +#! radius, and none of a hull. +pub val shape::radius: f32 { + get => this._radius; +} + +#! A sphere's middle, or a capsule's first end. +pub val shape::a: vec3 { + get => this._a; +} + +#! A capsule's second end, or a sphere's middle. +pub val shape::b: vec3 { + get => this._b; +} + +#! A hull's corners and faces. +pub def shape::as_hull(&this): &hull { + return &this._hull; +} + +#! The box holding it, where a pose places it. +pub def shape::bounds(&this, at: pose): bounds { + if this._kind == shape_kind::hull { + val m := mat3::rotation(at.turn); + var low := m * this._hull.point(0); + var high := low; + for i in 1..this._hull.count { + val p := m * this._hull.point(i); + low = low.min(p); + high = high.max(p); + } + return bounds{ at.at + low, at.at + high }; + } + val a := at.apply(this._a); + val b := at.apply(this._b); + val r := vec3{ this._radius, this._radius, this._radius }; + return bounds{ a.min(b) - r, a.max(b) + r }; +} + +#! Whether it holds a place of space, where a pose places it, its surface +#! among it. +pub def shape::contains(&this, at: pose, p: vec3): bool { + val local := at.unapply(p); + if this._kind == shape_kind::hull { + for f in 0..this._hull.faces { + return false if this._hull.normal(f).dot(local) > this._hull.offset(f); + } + return true; + } + val nearest := nearest_on_segment(local, this._a, this._b); + return (local - nearest).length_squared <= this._radius * this._radius; +} + +#! Where a ray first meets it, where a pose places it: from a place, along a +#! direction of length 1, as far as `reach`. A ray beginning within it meets +#! it at 0, facing back along the ray. +pub def shape::ray_cast(&this, at: pose, origin: vec3, direction: vec3, reach: f32): maybe { + val o := at.unapply(origin); + val d := at.unrotate(direction); + var found: maybe = nothing{}; + if this._kind == shape_kind::hull { + found = ray_hull(&this._hull, o, d, reach); + } else if this._kind == shape_kind::capsule { + found = ray_capsule(o, d, reach, this._a, this._b, this._radius); + } else { + found = ray_sphere(o, d, reach, this._a, this._radius); + } + if found is some(hit) { + return ray_hit{ distance = hit.distance, point = at.apply(hit.point), normal = at.rotate(hit.normal) }; + } + return nothing{}; +} + +# A ray, of the shape's own places, meeting a sphere. +def ray_sphere(o: vec3, d: vec3, reach: f32, center: vec3, radius: f32): maybe { + val s := o - center; + val c := s.dot(s) - radius * radius; + return ray_hit{ distance = 0, point = o, normal = -d } if c <= 0; + val b := s.dot(d); + return nothing{} if b > 0; + val disc := b * b - c; + return nothing{} if disc < 0; + val t := -b - math::sqrt(disc); + return nothing{} if t > reach; + val p := o + d * t; + return ray_hit{ distance = t, point = p, normal = (p - center) * (1 / radius) }; +} + +# A ray meeting a capsule: its round side, where it meets it between its ends, +# as an infinite cylinder's, else its round ends. +def ray_capsule(o: vec3, d: vec3, reach: f32, a: vec3, b: vec3, radius: f32): maybe { + val nearest := nearest_on_segment(o, a, b); + return ray_hit{ distance = 0, point = o, normal = -d } if (o - nearest).length_squared <= radius * radius; + # The cylinder, as Ericson's Real-Time Collision Detection meets one: where + # the ray's distance from its axis is the radius. + val axis := b - a; + val m := o - a; + val dd := axis.dot(axis); + val md := m.dot(axis); + val nd := d.dot(axis); + val qa := dd - nd * nd; + if qa > tiny { + val qb := dd * m.dot(d) - nd * md; + val qc := dd * (m.dot(m) - radius * radius) - md * md; + val disc := qb * qb - qa * qc; + if disc >= 0 { + val t := (-qb - math::sqrt(disc)) / qa; + val along := md + t * nd; + if t >= 0 && t <= reach && along >= 0 && along <= dd { + val p := o + d * t; + val on_axis := a + axis * (along / dd); + return ray_hit{ distance = t, point = p, normal = (p - on_axis) * (1 / radius) }; + } + } + } + var best: maybe = nothing{}; + val first := ray_sphere(o, d, reach, a, radius); + val second := ray_sphere(o, d, reach, b, radius); + if first is some(hit) { + best = hit; + } + if second is some(hit) { + if best is some(held) { + if hit.distance < held.distance { + best = hit; + } + } else { + best = hit; + } + } + return best; +} + +# A ray meeting a hull, clipped by each face's side in turn, as Cyrus and Beck +# clip a line: where it enters the last side it crosses into is where it meets +# the hull. +def ray_hull(h: &hull, o: vec3, d: vec3, reach: f32): maybe { + var lower: f32 = 0; + var upper := reach; + var entered: i64 = -1; + for f in 0..h.faces { + val n := h.normal(f); + val numerator := h.offset(f) - n.dot(o); + val denominator := n.dot(d); + if denominator == 0 { + return nothing{} if numerator < 0; + continue; + } + val t := numerator / denominator; + if denominator < 0 && t > lower { + lower = t; + entered = f as i64; + } else if denominator > 0 && t < upper { + upper = t; + } + return nothing{} if upper < lower; + } + return ray_hit{ distance = 0, point = o, normal = -d } if entered < 0; + return ray_hit{ distance = lower, point = o + d * lower, normal = h.normal(entered as u32) }; +} diff --git a/physics3d/sleep.sakura b/physics3d/sleep.sakura new file mode 100644 index 0000000..c071a09 --- /dev/null +++ b/physics3d/sleep.sakura @@ -0,0 +1,119 @@ +#! Contains how a space's bodies sleep: those that touch, or a joint holds +#! together, are an island, found anew each step, and an island sleeps when +#! all its bodies have been still for half a second, so a settled pile costs +#! nothing until something wakes it. A kinematic body sleeps alone, when it +#! has been still as long. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics3d; + +# How long, in seconds, a body is still before it may sleep. +const time_to_sleep: f32 = 0.5; + +# The first body of the island a body is of, each body passed on the way +# pointed nearer it, so the next finding is shorter. +def root_of(parent: &mut vector, b: u32): u32 { + var x := b; + while parent[x as u64] != x { + val up := parent[parent[x as u64] as u64]; + parent[x as u64] = up; + x = up; + } + return x; +} + +def join(parent: &mut vector, a: u32, b: u32): void { + val ra := root_of(parent, a); + val rb := root_of(parent, b); + if ra != rb { + parent[math::max(ra, rb) as u64] = math::min(ra, rb); + } +} + +# Finds the islands of awake dynamic bodies, and puts to sleep those all of +# whose bodies have been still long enough. +def space::sleep_islands(&mut this, dt: f32): void { + var parent := move(this.islands); + parent.clear(); + parent.resize(this.bodies.length, none); + for b in 0..this.bodies.length { + val body := &this.bodies[b]; + if body.alive && body.awake && body.kind == body_kind::dynamic { + parent[b] = b as u32; + } + } + for k in 0..this.contacts.length { + val c := &this.contacts[k]; + continue if !c.alive || !c.touching; + val a := c.body_a; + val b := c.body_b; + if parent[a as u64] != none && parent[b as u64] != none { + join(&mut parent, a, b); + } else if parent[a as u64] != none && this.bodies[b as u64].kind == body_kind::kinematic { + this.keep_awake_on(a, b); + } else if parent[b as u64] != none && this.bodies[a as u64].kind == body_kind::kinematic { + this.keep_awake_on(b, a); + } + } + this.join_jointed(&mut parent); + # Each island's least time still, kept at its root. + for b in 0..this.bodies.length { + continue if parent[b] == none; + val root := root_of(&mut parent, b as u32) as u64; + this.bodies[root].sleep_time = math::min(this.bodies[root].sleep_time, this.bodies[b].sleep_time); + } + for b in 0..this.bodies.length { + continue if parent[b] == none; + val root := root_of(&mut parent, b as u32); + continue if this.bodies[root as u64].sleep_time < time_to_sleep; + # Linked after its root, which heads the group. + this.bodies[b].awake = false; + this.bodies[b].velocity = vec3::zero; + this.bodies[b].spin = vec3::zero; + this.bodies[b].group = root; + if b as u32 != root { + this.bodies[b].next_in_group = this.bodies[root as u64].next_in_group; + this.bodies[root as u64].next_in_group = b as u32; + } + } + # A kinematic body still long enough sleeps alone. + for b in 0..this.bodies.length { + val body := &this.bodies[b]; + if body.alive && body.awake && body.kind == body_kind::kinematic && body.sleep_time >= time_to_sleep { + this.bodies[b].awake = false; + this.bodies[b].group = b as u32; + } + } + this.islands = move(parent); +} + +# Keeps a dynamic body awake where it rests on a kinematic body that moves. +def space::keep_awake_on(&mut this, b: u32, kinematic: u32): void { + val k := &this.bodies[kinematic as u64]; + if k.velocity.length_squared > 0 || k.spin.length_squared > 0 { + this.bodies[b as u64].sleep_time = 0; + } +} + +# Wakes a body, and every body of the group it sleeps with, and marks it as +# having been still for no time. +def space::wake_body(&mut this, b: u32): void { + return if this.bodies[b as u64].kind == body_kind::static; + this.bodies[b as u64].sleep_time = 0; + return if this.bodies[b as u64].awake; + var m := this.bodies[b as u64].group; + if m == none { + this.bodies[b as u64].awake = true; + return; + } + while m != none { + val next := this.bodies[m as u64].next_in_group; + this.bodies[m as u64].awake = true; + this.bodies[m as u64].sleep_time = 0; + this.bodies[m as u64].group = none; + this.bodies[m as u64].next_in_group = none; + m = next; + } +} diff --git a/physics3d/solver.sakura b/physics3d/solver.sakura new file mode 100644 index 0000000..3ed5cca --- /dev/null +++ b/physics3d/solver.sakura @@ -0,0 +1,491 @@ +#! Contains how a space solves a step, as Box2D's soft step solves one: in +#! substeps, each of which moves velocities by forces, pushes apart what meets, +#! softly, moves the bodies, and pushes again without undoing overlaps; then +#! bounces what met fast enough, and keeps each contact's impulses for the +#! next step to begin with. +#! +#! A contact pushes as a stiff, damped spring of the space's frequency, so an +#! overlap is undone over a few substeps, no faster than the push speed, and a +#! stack doesn't jitter. Points apart within the speculative margin push only +#! as much as would close the gap in a substep, so what falls stops at what's +#! below it rather than in it. Friction holds each point along two tangents at +#! once, no harder in all than its share of what pushes it, as a cone allows. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics3d; + +# How soft a constraint is, as a damped spring of a frequency is: how much of +# its error it undoes each second, and how much of its impulse it gives. +struct softness { + var bias_rate: f32; + var mass_scale: f32 = 1; + var impulse_scale: f32; +} + +def soft_of(hertz: f32, damping: f32, h: f32): softness { + return softness{} if hertz == 0; + val omega := 2 * math::pi as f32 * hertz; + val a1 := 2 * damping + h * omega; + val a2 := h * omega * a1; + val a3 := 1 / (1 + a2); + return softness{ bias_rate = omega / a1, mass_scale = a2 * a3, impulse_scale = a3 }; +} + +# A body as a step moves it: its velocities, and how far its center has moved +# and it has turned since the step began. +struct body_state { + var v: vec3; + var w: vec3; + var dp: vec3; + var dq: quat; +} + +# How a body's velocities change each substep: by its forces and gravity, and +# what its damping keeps of them. +struct body_motion { + var dv: vec3; + var dw: vec3; + var linear_keep: f32 = 1; + var angular_keep: f32 = 1; +} + +# A point of a contact as the solver pushes at it: where it is from each +# body's center, how far apart the two are there but for how far they've +# moved, and the impulses pushing them apart and along each tangent. +struct point_constraint { + var anchor_a: vec3; + var anchor_b: vec3; + var base_separation: f32; + var normal_impulse: f32; + var tangent_impulse: vec3; + var max_impulse: f32; + var impact: f32; # What stopped it meeting fast, as the step began. + var normal_mass: f32; + var tangent_mass: vec3; + var relative_velocity: f32; +} + +struct contact_constraint { + var a: u32; # States. + var b: u32; + var contact: u32; + var normal: vec3; + var t1: vec3; + var t2: vec3; + var friction: f32; + var restitution: f32; + var ma: f32; + var mb: f32; + var soft: softness; + var count: u32; + var points: point_constraint[4]; +} + +# What a step works in, kept from one to the next so it isn't made anew: the +# first state is of what doesn't move, of no mass and turning by nothing. +struct solver_scratch { + var states: vector; + var motions: vector; + var inertias: vector; # Each state's inverse inertia, of space's axes. + var bodies: vector; + var constraints: vector; + var joints: vector; + var joint_soft: softness; + var wide: vector; + var overflow: vector; # Constraints of no color. + var colored: vector; # Each color's bodies, a bit each. + var color_of: vector; + var color_groups: u32[25]; # Where each color's lanes begin. +} + +# The most a body turns in a substep, a quarter of a half turn, so a fast spin +# doesn't skip through what it meets. +const most_turn: f32 = 0.25 * 3.14159265; + +# A rotation turned further by a spin over a time, kept of length 1. +def turned(q: quat, w: vec3, h: f32): quat { + val spin := quat{ w.x, w.y, w.z, 0 } * q; + val half := 0.5 * h; + return quat{ q.x + half * spin.x, q.y + half * spin.y, q.z + half * spin.z, q.w + half * spin.w }.normalized(); +} + +# How hard it is to push the two along a direction at their anchors. +def mass_along(d: vec3, ra: vec3, rb: vec3, ma: f32, mb: f32, ia: mat3, ib: mat3): f32 { + val rda := ra.cross(d); + val rdb := rb.cross(d); + val k := ma + mb + rda.dot(ia * rda) + rdb.dot(ib * rdb); + return k > 0 ? 1 / k : 0f; +} + +def space::solve(&mut this, dt: f32): void { + val n: u32 = this.substeps > 0 ? this.substeps : 1; + val h := dt / n as f32; + val inv_h := 1 / h; + var s := move(this.solver); + this.gather(&mut s, h); + this.prepare_contacts(&mut s, h); + this.prepare_joints(&mut s, h); + stop_impacts(&mut s, dt, 2 * this.push_speed); + color_contacts(&mut s); + val max_spin := most_turn * inv_h; + this.crew.start(this.threads); + for i in 0..n { + integrate_velocities(&mut s, this.max_speed, max_spin); + this.warm_joints(&mut s); + this.wide_stage(&mut s, true, inv_h, this.push_speed, true); + warm_contacts(&mut s); + this.solve_joints(&mut s, h, true); + this.wide_stage(&mut s, false, inv_h, this.push_speed, true); + solve_contacts(&mut s, inv_h, this.push_speed, true); + integrate_positions(&mut s, h); + this.solve_joints(&mut s, h, false); + this.wide_stage(&mut s, false, inv_h, this.push_speed, false); + solve_contacts(&mut s, inv_h, this.push_speed, false); + } + unpack_contacts(&mut s); + bounce(&mut s, this.restitution_threshold); + this.keep_impulses(&s); + this.finish(&s, dt); + this.solver = move(s); +} + +# Gives each moving body a state, its inverse inertia as it's turned, and how +# its forces move it each substep. +def space::gather(&mut this, s: &mut solver_scratch, h: f32): void { + s.states.clear(); + s.motions.clear(); + s.inertias.clear(); + s.bodies.clear(); + s.states.append(body_state{ dq = quat::identity }); + s.motions.append(body_motion{}); + s.inertias.append(mat3{}); + s.bodies.append(none); + for b in 0..this.bodies.length { + if !this.bodies[b].alive || !this.moves(b as u32) { + this.bodies[b].slot = 0; + continue; + } + this.bodies[b].slot = s.states.length as u32; + val inverse := this.world_inverse_inertia(b as u32); + val body := &this.bodies[b]; + s.states.append(body_state{ v = body.velocity, w = body.spin, dq = quat::identity }); + s.inertias.append(inverse); + if body.kind == body_kind::dynamic { + s.motions.append(body_motion{ + dv = ((this.gravity + body.gravity) * body.gravity_scale + body.force * body.inv_mass) * h, + dw = (inverse * body.torque) * h, + linear_keep = 1 / (1 + h * body.linear_damping), + angular_keep = 1 / (1 + h * body.angular_damping), + }); + } else { + s.motions.append(body_motion{}); + } + s.bodies.append(b as u32); + } +} + +def space::prepare_contacts(&this, s: &mut solver_scratch, h: f32): void { + s.constraints.clear(); + val hertz := math::min(this.contact_hertz, 0.25 / h); + val soft := soft_of(hertz, this.contact_damping, h); + # Against what doesn't move, twice as stiff. + val stiff := soft_of(2 * hertz, this.contact_damping, h); + for k in 0..this.contacts.length { + val c := &this.contacts[k]; + continue if !c.alive || !c.touching; + val a := &this.bodies[c.body_a as u64]; + val b := &this.bodies[c.body_b as u64]; + continue if a.slot == 0 && b.slot == 0; + val ia := s.inertias[a.slot as u64]; + val ib := s.inertias[b.slot as u64]; + val n := c.manifold.normal; + val t1 := perpendicular_to(n); + val t2 := n.cross(t1); + var made := contact_constraint{ + a = a.slot, b = b.slot, contact = k as u32, normal = n, t1 = t1, t2 = t2, friction = c.friction, restitution = c.restitution, + ma = a.inv_mass, mb = b.inv_mass, soft = a.inv_mass == 0 || b.inv_mass == 0 ? stiff : soft, count = c.manifold.count, + }; + for j in 0..c.manifold.count { + val mp := &c.manifold.points[j]; + val ra := mp.point - a.center; + val rb := mp.point - b.center; + val vra := a.velocity + a.spin.cross(ra); + val vrb := b.velocity + b.spin.cross(rb); + # The tangents' impulses kept as they were along last step's tangents, + # which turn with the normal: what of them lies along these. + made.points[j] = point_constraint{ + anchor_a = ra, anchor_b = rb, + base_separation = -mp.depth - (rb - ra).dot(n), + normal_impulse = c.normal_impulse[j], tangent_impulse = c.tangent_impulse[j], + normal_mass = mass_along(n, ra, rb, made.ma, made.mb, ia, ib), + tangent_mass = vec3{ mass_along(t1, ra, rb, made.ma, made.mb, ia, ib), mass_along(t2, ra, rb, made.ma, made.mb, ia, ib), 0 }, + relative_velocity = n.dot(vrb - vra), + }; + } + s.constraints.append(made); + } +} + +# Stops what meets faster than a threshold before the substeps begin, as far +# as closes its gap through the step, over a few passes, so a crate dropped +# flat lands flat: solved within the substeps, the impulse that stops it would +# be given again as each begins, and taken back, unevenly between its points, +# throwing it. What stops it is kept apart from the impulses the substeps +# begin with, but for bouncing. +def stop_impacts(s: &mut solver_scratch, dt: f32, threshold: f32): void { + for pass in 0..4u { + for i in 0..s.constraints.length { + val c := &mut s.constraints[i]; + var fast := false; + for j in 0..c.count { + if c.points[j].relative_velocity < -threshold { + fast = true; + } + } + continue if !fast; + val ia := s.inertias[c.a as u64]; + val ib := s.inertias[c.b as u64]; + var va := s.states[c.a as u64].v; + var wa := s.states[c.a as u64].w; + var vb := s.states[c.b as u64].v; + var wb := s.states[c.b as u64].w; + val n := c.normal; + for j in 0..c.count { + val cp := &mut c.points[j]; + val ra := cp.anchor_a; + val rb := cp.anchor_b; + val gap := cp.base_separation + (rb - ra).dot(n); + val least := gap > 0 ? -gap / dt : 0f; + val vn := (vb + wb.cross(rb) - va - wa.cross(ra)).dot(n); + val sum := math::max(cp.impact - cp.normal_mass * (vn - least), 0f); + val impulse := sum - cp.impact; + cp.impact = sum; + cp.max_impulse = math::max(cp.max_impulse, sum); + val p := n * impulse; + va = va - p * c.ma; + wa = wa - ia * ra.cross(p); + vb = vb + p * c.mb; + wb = wb + ib * rb.cross(p); + } + s.states[c.a as u64].v = va; + s.states[c.a as u64].w = wa; + s.states[c.b as u64].v = vb; + s.states[c.b as u64].w = wb; + } + } +} + +def integrate_velocities(s: &mut solver_scratch, max_speed: f32, max_spin: f32): void { + for i in 1..s.states.length { + val m := &s.motions[i]; + val st := &mut s.states[i]; + var v := st.v * m.linear_keep + m.dv; + var w := st.w * m.angular_keep + m.dw; + val speed_squared := v.length_squared; + if speed_squared > max_speed * max_speed { + v = v * (max_speed / math::sqrt(speed_squared)); + } + val spin_squared := w.length_squared; + if spin_squared > max_spin * max_spin { + w = w * (max_spin / math::sqrt(spin_squared)); + } + st.v = v; + st.w = w; + } +} + +def integrate_positions(s: &mut solver_scratch, h: f32): void { + for i in 1..s.states.length { + val st := &mut s.states[i]; + st.dq = turned(st.dq, st.w, h); + st.dp = st.dp + st.v * h; + } +} + +# Of the contacts of no color, one at a time. +def warm_contacts(s: &mut solver_scratch): void { + for o in 0..s.overflow.length { + val c := &s.constraints[s.overflow[o] as u64]; + val ia := s.inertias[c.a as u64]; + val ib := s.inertias[c.b as u64]; + var va := s.states[c.a as u64].v; + var wa := s.states[c.a as u64].w; + var vb := s.states[c.b as u64].v; + var wb := s.states[c.b as u64].w; + for j in 0..c.count { + val cp := &c.points[j]; + val p := c.normal * cp.normal_impulse + c.t1 * cp.tangent_impulse.x + c.t2 * cp.tangent_impulse.y; + va = va - p * c.ma; + wa = wa - ia * cp.anchor_a.cross(p); + vb = vb + p * c.mb; + wb = wb + ib * cp.anchor_b.cross(p); + } + s.states[c.a as u64].v = va; + s.states[c.a as u64].w = wa; + s.states[c.b as u64].v = vb; + s.states[c.b as u64].w = wb; + } +} + +def solve_contacts(s: &mut solver_scratch, inv_h: f32, push: f32, use_bias: bool): void { + val states := s.states.slice; + val constraints := s.constraints.slice; + for o in 0..s.overflow.length { + val c := &mut constraints[s.overflow[o] as u64]; + val a := c.a as u64; + val b := c.b as u64; + val ia := s.inertias[a]; + val ib := s.inertias[b]; + var va := states[a].v; + var wa := states[a].w; + var vb := states[b].v; + var wb := states[b].w; + val dp := states[b].dp - states[a].dp; + val qa := mat3::rotation(states[a].dq); + val qb := mat3::rotation(states[b].dq); + val n := c.normal; + for j in 0..c.count { + val cp := &mut c.points[j]; + val ra := cp.anchor_a; + val rb := cp.anchor_b; + # How far apart they are now: as they began, and as far as each anchor + # has moved and turned since. + val d := dp + (qb * rb - qa * ra); + val separation := d.dot(n) + cp.base_separation; + var bias: f32 = 0; + var mass_scale: f32 = 1; + var impulse_scale: f32 = 0; + if separation > 0 { + bias = separation * inv_h; + } else if use_bias { + bias = c.soft.bias_rate * separation; + if bias < -push { + bias = -push; + } + mass_scale = c.soft.mass_scale; + impulse_scale = c.soft.impulse_scale; + } + val vn := (vb + wb.cross(rb) - va - wa.cross(ra)).dot(n); + val before := cp.normal_impulse; + var sum := before - cp.normal_mass * mass_scale * (vn + bias) - impulse_scale * before; + if sum < 0 { + sum = 0; + } + val impulse := sum - before; + cp.normal_impulse = sum; + if impulse > cp.max_impulse { + cp.max_impulse = impulse; + } + val p := n * impulse; + va = va - p * c.ma; + wa = wa - ia * ra.cross(p); + vb = vb + p * c.mb; + wb = wb + ib * rb.cross(p); + } + # Friction along both tangents, of no more in all than its share of what + # pushes them apart. + for j in 0..c.count { + val cp := &mut c.points[j]; + val ra := cp.anchor_a; + val rb := cp.anchor_b; + val dv := vb + wb.cross(rb) - va - wa.cross(ra); + val before := cp.tangent_impulse; + var sum := vec3{ before.x - cp.tangent_mass.x * dv.dot(c.t1), before.y - cp.tangent_mass.y * dv.dot(c.t2), 0 }; + val most := c.friction * cp.normal_impulse; + val squared := sum.x * sum.x + sum.y * sum.y; + if squared > most * most { + sum = sum * (most / math::sqrt(squared)); + } + cp.tangent_impulse = sum; + val p := c.t1 * (sum.x - before.x) + c.t2 * (sum.y - before.y); + va = va - p * c.ma; + wa = wa - ia * ra.cross(p); + vb = vb + p * c.mb; + wb = wb + ib * rb.cross(p); + } + states[a].v = va; + states[a].w = wa; + states[b].v = vb; + states[b].w = wb; + } +} + +# Bounces what met faster than the threshold, as much as its restitution +# keeps of how fast it met: only at points that pushed, so a speculative +# point that never closed doesn't bounce. +def bounce(s: &mut solver_scratch, threshold: f32): void { + for i in 0..s.constraints.length { + val c := &mut s.constraints[i]; + continue if c.restitution == 0; + val ia := s.inertias[c.a as u64]; + val ib := s.inertias[c.b as u64]; + var va := s.states[c.a as u64].v; + var wa := s.states[c.a as u64].w; + var vb := s.states[c.b as u64].v; + var wb := s.states[c.b as u64].w; + val n := c.normal; + for j in 0..c.count { + val cp := &mut c.points[j]; + continue if cp.relative_velocity > -threshold || cp.max_impulse == 0; + val vn := (vb + wb.cross(cp.anchor_b) - va - wa.cross(cp.anchor_a)).dot(n); + var impulse := -cp.normal_mass * (vn + c.restitution * cp.relative_velocity); + val sum := math::max(cp.normal_impulse + impulse, 0f); + impulse = sum - cp.normal_impulse; + cp.normal_impulse = sum; + cp.max_impulse = math::max(cp.max_impulse, impulse); + val p := n * impulse; + va = va - p * c.ma; + wa = wa - ia * cp.anchor_a.cross(p); + vb = vb + p * c.mb; + wb = wb + ib * cp.anchor_b.cross(p); + } + s.states[c.a as u64].v = va; + s.states[c.a as u64].w = wa; + s.states[c.b as u64].v = vb; + s.states[c.b as u64].w = wb; + } +} + +def space::keep_impulses(&mut this, s: &solver_scratch): void { + for i in 0..s.constraints.length { + val c := &s.constraints[i]; + for j in 0..c.count { + this.contacts[c.contact as u64].normal_impulse[j] = c.points[j].normal_impulse; + this.contacts[c.contact as u64].tangent_impulse[j] = c.points[j].tangent_impulse; + } + } +} + +# Puts each moving body where its state moved it, its colliders' leaves with +# it, and times how long it's been still. +def space::finish(&mut this, s: &solver_scratch, dt: f32): void { + val still := 0.05 * this.unit; + for i in 1..s.states.length { + val b := s.bodies[i] as u64; + val st := &s.states[i]; + val began := this.bodies[b].center; + val turned_from := this.bodies[b].at.turn; + val center := began + st.dp; + val turn := (st.dq * turned_from).normalized(); + this.bodies[b].center = center; + this.bodies[b].at = pose{ at = center - turn * this.bodies[b].local_center, turn = turn }; + this.bodies[b].velocity = st.v; + this.bodies[b].spin = st.w; + this.bodies[b].force = vec3::zero; + this.bodies[b].torque = vec3::zero; + val speed := st.v.length + st.w.length * this.bodies[b].extent; + if !this.bodies[b].can_sleep || speed > still { + this.bodies[b].sleep_time = 0; + } else { + this.bodies[b].sleep_time += dt; + } + val count := this.fast.length; + this.note_fast(b as u32, sweep{ local_center = this.bodies[b].local_center, c1 = began, c2 = center, q1 = turned_from, q2 = turn }); + if this.fast.length == count { + this.place_colliders(b as u32); + } + } + this.sweep_fast(); +} diff --git a/physics3d/space.sakura b/physics3d/space.sakura new file mode 100644 index 0000000..b6a1610 --- /dev/null +++ b/physics3d/space.sakura @@ -0,0 +1,505 @@ +#! Contains `space`, where bodies move: each made of colliders, pulled by +#! gravity, pushed by forces and by what they meet, and stepped forward in +#! time, as `physics2d`'s space steps them in a plane. +#! +#! A step finds the colliders newly near one another, by the boxes of its +#! tree; where those near meet, as contacts kept from the last step, a +#! triangle mesh's one for each triangle met; and then solves them, in +#! substeps, as Box2D's soft step does: each substep moves the bodies' +#! velocities by their forces, pushes them apart where they meet, softly so a +#! deep overlap is undone over a few steps rather than at once, moves them, and +#! pushes again without undoing overlaps, so what was pushed apart doesn't fly. +#! Each contact begins a step with the impulses it ended the last with, so a +#! stack settles and stays still. Bodies that rest long enough, with all they +#! touch, sleep until something wakes them. +#! +#! Lengths are a game's units, and its tolerances are made for a unit of a +#! meter: a space of another unit is made with how many units a meter is. + +import std::containers; +import std::math; +import std::time; +import malunal::geometry; +import malunal::linear; +module malunal::physics3d; + +#! Where bodies move, as one step after another moves them. +pub struct space { + #! The pull on every dynamic body, in lengths a second each second. + pub var gravity := vec3{ 0, -10, 0 }; + #! How many substeps each step is solved in: more is stiffer and slower. + pub var substeps: u32 = 4; + #! How stiff contacts are, as a spring of so many cycles a second, and how + #! much they're damped: past 1, they don't spring back. + pub var contact_hertz: f32 = 30; + pub var contact_damping: f32 = 10; + #! The same of joints. + pub var joint_hertz: f32 = 60; + pub var joint_damping: f32 = 2; + #! The fastest a contact pushes overlapping bodies apart, in lengths a + #! second. + pub var push_speed: f32 = 3; + #! How fast bodies must meet, in lengths a second, to bounce. + pub var restitution_threshold: f32 = 1; + #! How fast colliders must begin touching, in lengths a second, to be told + #! of as a hit. + pub var hit_speed: f32 = 1; + #! The fastest a body moves, in lengths a second. + pub var max_speed: f32 = 400; + #! Whether bodies at rest sleep. + pub var sleeping: bool = true; + #! Whether dynamic bodies moving fast are swept against what stands still, + #! so they never pass through what's thin. + pub var continuous: bool = true; + #! How many threads each step is solved on, its caller's among them: each + #! color of contacts split between them, so a step gives the same on any + #! number. 1 solves on the caller's alone. + pub var threads: u32 = 1; + #! How long the last step took, and each of its parts. + pub var profile: step_profile; + var crew: crew; + var found: vector; # Each pair's, found on the crew. + var unit: f32 = 1; + var fast: vector; + var bodies: vector; + var colliders: vector; + var meshes: vector; + var pairs: vector; + var contacts: vector; + var joints: vector; + var free_bodies: vector; + var free_colliders: vector; + var free_meshes: vector; + var free_pairs: vector; + var free_contacts: vector; + var free_joints: vector; + var tree: aabb_tree; + var pair_keys: dict; + var moved: vector; + var near: vector; + var met: vector; + var noted: vector; + var struck: vector; + var solver: solver_scratch; + var islands: vector; +} + +#! How long a step took, in milliseconds, and each of its parts: finding what +#! newly nears, where it meets, solving it, and finding what sleeps. +pub struct step_profile { + pub var pairs: f64; + pub var contacts: f64; + pub var solve: f64; + pub var sleep: f64; + pub var step: f64; +} + +#! A space of no bodies, pulled by a gravity: `unit` is how many of its lengths +#! a meter is, which its tolerances, push speed, bounce threshold, and top +#! speed are scaled by. +pub def space::new(gravity: vec3 = vec3{ 0, -10, 0 }, unit: f32 = 1): space { + return space{ + gravity = gravity, unit = unit, push_speed = 3 * unit, restitution_threshold = unit, hit_speed = unit, max_speed = 400 * unit, + tree = aabb_tree::new(0.1 * unit), pair_keys = dict::::new(), + }; +} + +# How near two surfaces are taken as touching: what contacts let them overlap +# by, and what they meet at before touching. +val space::slop: f32 { + get => 0.005 * this.unit; +} + +val space::speculative: f32 { + get => 4 * this.slop; +} + +#! How many bodies it holds. +pub val space::body_count: u64 { + get => this.bodies.length - this.free_bodies.length; +} + +#! How many contacts it holds: pairs of shapes, or a shape and a triangle, +#! near enough to meet. +pub val space::contact_count: u64 { + get => this.contacts.length - this.free_contacts.length; +} + +#! The contacts that began and ended touching in the last step. +pub def space::events(&this): span { + return this.noted.span; +} + +#! Adds a body, of no colliders yet. +pub def space::add(&mut this, made: body): body_id { + var index: u32 = 0; + if this.free_bodies.length > 0 { + index = this.free_bodies[this.free_bodies.length - 1]; + this.free_bodies.truncate(); + } else { + index = this.bodies.length as u32; + this.bodies.append(body_record{}); + } + val generation := this.bodies[index as u64].generation + 1; + val moving := made.kind != body_kind::static; + this.bodies[index as u64] = body_record{ + kind = made.kind, generation = generation, alive = true, at = made.at, center = made.at.at, + velocity = moving ? made.velocity : vec3::zero, spin = moving ? made.spin : vec3::zero, + linear_damping = made.linear_damping, angular_damping = made.angular_damping, gravity_scale = made.gravity_scale, + gravity = made.gravity, fixed_rotation = made.fixed_rotation, can_sleep = made.can_sleep, bullet = made.bullet, data = made.data, + }; + this.find_mass(index); + return body_id{ index = index, generation = generation }; +} + +#! Whether a body is of it still. +pub def space::has(&this, id: body_id): bool { + return id.index < this.bodies.length as u32 && this.bodies[id.index as u64].alive && this.bodies[id.index as u64].generation == id.generation; +} + +#! Removes a body, its colliders, the contacts they're of, and the joints it's +#! of, waking what it touched. +pub def space::remove(&mut this, id: body_id): void { + return if !this.has(id); + this.wake_body(id.index); + var c := this.bodies[id.index as u64].colliders; + while c != none { + val next := this.colliders[c as u64].next; + this.drop_collider(c); + c = next; + } + this.drop_joints_of(id.index); + this.bodies[id.index as u64].alive = false; + this.bodies[id.index as u64].colliders = none; + this.bodies[id.index as u64].group = none; + this.free_bodies.append(id.index); +} + +#! Gives a body a collider, its mass summed again of its colliders'. +pub def space::attach(&mut this, to: body_id, made: collider): collider_id { + return collider_id{} if !this.has(to); + return this.attach_record(to, collider_record{ made = made, body = to.index }); +} + +#! Gives a static body a heightfield's ground, as a terrain, met as a mesh's +#! triangles are. +pub def space::attach_heightfield(&mut this, to: body_id, field: heightfield, made: collider): collider_id { + var held := move(field); + return this.attach_mesh(to, triangle_mesh::of_field(move(held)), made); +} + +#! Gives a static body the triangles of a mesh, as a level's ground and walls, +#! which push what meets each as its face does, but at the edges two don't +#! fold at, so what slides across them doesn't catch. Its shape and density +#! are passed over; a mesh meets shapes, not another mesh. +pub def space::attach_mesh(&mut this, to: body_id, mesh: triangle_mesh, made: collider): collider_id { + var held := move(mesh); + return collider_id{} if !this.has(to); + var m: u32 = 0; + if this.free_meshes.length > 0 { + m = this.free_meshes[this.free_meshes.length - 1]; + this.free_meshes.truncate(); + this.meshes[m as u64] = move(held); + } else { + m = this.meshes.length as u32; + this.meshes.append(move(held)); + } + return this.attach_record(to, collider_record{ made = made, mesh = m, body = to.index }); +} + +def space::attach_record(&mut this, to: body_id, record: collider_record): collider_id { + var index: u32 = 0; + if this.free_colliders.length > 0 { + index = this.free_colliders[this.free_colliders.length - 1]; + this.free_colliders.truncate(); + } else { + index = this.colliders.length as u32; + this.colliders.append(collider_record{}); + } + val generation := this.colliders[index as u64].generation + 1; + var made := record; + made.next = this.bodies[to.index as u64].colliders; + made.generation = generation; + made.alive = true; + made.moved = true; + this.colliders[index as u64] = made; + val box := this.box_of(index, this.bodies[to.index as u64].at); + this.colliders[index as u64].leaf = this.tree.insert(box, index as u64); + this.bodies[to.index as u64].colliders = index; + this.moved.append(index); + this.find_mass(to.index); + this.wake_body(to.index); + return collider_id{ index = index, generation = generation }; +} + +# The box holding a collider, where a pose places its body. +def space::box_of(&this, c: u32, at: pose): bounds { + val record := &this.colliders[c as u64]; + return record.made.shape.bounds(at) if !record.is_mesh(); + val own := this.meshes[record.mesh as u64].bounds(); + var made := bounds::blank; + for k in 0..8u { + val corner := vec3{ (k & 1) != 0 ? own.max.x : own.min.x, (k & 2) != 0 ? own.max.y : own.min.y, (k & 4) != 0 ? own.max.z : own.min.z }; + made = made.including(at.apply(corner)); + } + return made; +} + +#! Whether a collider is of it still. +pub def space::has(&this, id: collider_id): bool { + return id.index < this.colliders.length as u32 && this.colliders[id.index as u64].alive && this.colliders[id.index as u64].generation == id.generation; +} + +#! Takes a collider from its body, its mass summed again of the rest. +pub def space::detach(&mut this, id: collider_id): void { + return if !this.has(id); + val b := this.colliders[id.index as u64].body; + var c := this.bodies[b as u64].colliders; + if c == id.index { + this.bodies[b as u64].colliders = this.colliders[c as u64].next; + } else { + while c != none { + val next := this.colliders[c as u64].next; + if next == id.index { + this.colliders[c as u64].next = this.colliders[next as u64].next; + break; + } + c = next; + } + } + this.drop_collider(id.index); + this.find_mass(b); + this.wake_body(b); +} + +# Frees a collider, its leaf, its mesh, and its pairs. +def space::drop_collider(&mut this, c: u32): void { + for p in 0..this.pairs.length { + if this.pairs[p].alive && (this.pairs[p].a == c || this.pairs[p].b == c) { + this.drop_pair(p as u32, true); + } + } + this.tree.remove(this.colliders[c as u64].leaf); + if this.colliders[c as u64].is_mesh() { + val m := this.colliders[c as u64].mesh; + this.meshes[m as u64] = triangle_mesh::new(span::::blank(), span::::blank()); + this.free_meshes.append(m); + } + this.colliders[c as u64].alive = false; + this.free_colliders.append(c); +} + +#! The body a collider is of. +pub def space::body_of(&this, id: collider_id): body_id { + return body_id{} if !this.has(id); + val b := this.colliders[id.index as u64].body; + return body_id{ index = b, generation = this.bodies[b as u64].generation }; +} + +#! What a collider was made as. +pub def space::collider_of(&this, id: collider_id): &collider { + return &this.colliders[id.index as u64].made; +} + +#! The number its user gave a body. +pub def space::data_of(&this, id: body_id): u64 { + return this.bodies[id.index as u64].data; +} + +#! What kind of body it is. +pub def space::kind_of(&this, id: body_id): body_kind { + return this.bodies[id.index as u64].kind; +} + +#! Where a body is, and which way it's turned. +pub def space::pose_of(&this, id: body_id): pose { + return this.bodies[id.index as u64].at; +} + +#! How fast a body's center of mass moves, and how fast it turns. +pub def space::velocity_of(&this, id: body_id): vec3 { + return this.bodies[id.index as u64].velocity; +} + +pub def space::spin_of(&this, id: body_id): vec3 { + return this.bodies[id.index as u64].spin; +} + +#! A body's mass, its center of its own places, and its inertia tensor about +#! that center. +pub def space::mass_of(&this, id: body_id): mass_data { + val b := &this.bodies[id.index as u64]; + return mass_data{ mass = b.mass, center = b.local_center, inertia = b.inertia }; +} + +#! Where a body's center of mass is in space. +pub def space::center_of(&this, id: body_id): vec3 { + return this.bodies[id.index as u64].center; +} + +#! Whether a body is awake, as it is but where it and all it rests on have +#! been still long enough. +pub def space::is_awake(&this, id: body_id): bool { + return this.bodies[id.index as u64].awake; +} + +#! Puts a body somewhere, as it is at once, waking it. +pub def space::set_pose(&mut this, id: body_id, at: pose): void { + return if !this.has(id); + this.bodies[id.index as u64].at = at; + this.bodies[id.index as u64].center = at.apply(this.bodies[id.index as u64].local_center); + this.place_colliders(id.index); + this.wake_body(id.index); +} + +#! Sets how fast a body moves, waking it. +pub def space::set_velocity(&mut this, id: body_id, velocity: vec3): void { + return if !this.has(id) || this.bodies[id.index as u64].kind == body_kind::static; + this.bodies[id.index as u64].velocity = velocity; + if velocity.length_squared > 0 { + this.wake_body(id.index); + } +} + +#! Sets how fast a body turns, waking it. +pub def space::set_spin(&mut this, id: body_id, spin: vec3): void { + return if !this.has(id) || this.bodies[id.index as u64].kind == body_kind::static || this.bodies[id.index as u64].fixed_rotation; + this.bodies[id.index as u64].spin = spin; + if spin.length_squared > 0 { + this.wake_body(id.index); + } +} + +#! Sets a body's own gravity, added to the space's, as a planet's pull changes +#! as the body goes around it; waking it where that turns or grows it by more +#! than a hundredth, so a body asleep stays so as the pull is found again. +pub def space::set_gravity(&mut this, id: body_id, gravity: vec3): void { + return if !this.has(id); + val i := id.index as u64; + val was := this.bodies[i].gravity; + this.bodies[i].gravity = gravity; + if (gravity - was).length_squared > 1e-4 * math::max(gravity.length_squared, was.length_squared) { + this.wake_body(id.index); + } +} + +#! A body's own gravity, added to the space's. +pub def space::gravity_of(&this, id: body_id): vec3 { + return this.bodies[id.index as u64].gravity; +} + +#! Pushes a dynamic body through the next step by a force at a place of space, +#! which turns it too where that's off its center, waking it. +pub def space::apply_force(&mut this, id: body_id, force: vec3, at: vec3): void { + return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic(); + val i := id.index as u64; + this.bodies[i].force = this.bodies[i].force + force; + this.bodies[i].torque = this.bodies[i].torque + (at - this.bodies[i].center).cross(force); + this.wake_body(id.index); +} + +#! Pushes a dynamic body through the next step by a force at its center, +#! waking it. +pub def space::apply_force_to_center(&mut this, id: body_id, force: vec3): void { + return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic(); + this.bodies[id.index as u64].force = this.bodies[id.index as u64].force + force; + this.wake_body(id.index); +} + +#! Turns a dynamic body through the next step by a torque, waking it. +pub def space::apply_torque(&mut this, id: body_id, torque: vec3): void { + return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic(); + this.bodies[id.index as u64].torque = this.bodies[id.index as u64].torque + torque; + this.wake_body(id.index); +} + +#! Changes how fast a dynamic body moves and turns at once, as a blow at a +#! place of space does, waking it. +pub def space::apply_impulse(&mut this, id: body_id, impulse: vec3, at: vec3): void { + return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic(); + val i := id.index as u64; + this.bodies[i].velocity = this.bodies[i].velocity + impulse * this.bodies[i].inv_mass; + this.bodies[i].spin = this.bodies[i].spin + this.world_inverse_inertia(id.index) * (at - this.bodies[i].center).cross(impulse); + this.wake_body(id.index); +} + +#! Wakes a body, and those it sleeps with. +pub def space::wake(&mut this, id: body_id): void { + if this.has(id) { + this.wake_body(id.index); + } +} + +# A body's inverse inertia tensor, of space's axes as it's turned. +def space::world_inverse_inertia(&this, b: u32): mat3 { + val body := &this.bodies[b as u64]; + val r := mat3::rotation(body.at.turn); + return r * body.inv_inertia * r.transposed(); +} + +# Sums a body's mass of its colliders', where it's dynamic, and how far they +# reach from its center. +def space::find_mass(&mut this, b: u32): void { + var sum := mass_data{}; + if this.bodies[b as u64].is_dynamic() { + var c := this.bodies[b as u64].colliders; + while c != none { + val record := &this.colliders[c as u64]; + if !record.is_mesh() && record.made.density > 0 { + sum = sum.add(record.made.shape.mass(record.made.density)); + } + c = record.next; + } + } + var mass: f32 = 0; + var inertia := mat3{}; + var inverse := mat3{}; + var local := vec3::zero; + if this.bodies[b as u64].is_dynamic() { + # A dynamic body of no mass moves as one of 1. + mass = sum.mass > 0 ? sum.mass : 1f; + local = sum.center; + if sum.mass > 0 && !this.bodies[b as u64].fixed_rotation && sum.inertia.determinant > 0 { + inertia = sum.inertia; + inverse = sum.inertia.inverse(); + } + } + var extent: f32 = 0; + var least: f32 = 0; + var c := this.bodies[b as u64].colliders; + while c != none { + val record := &this.colliders[c as u64]; + if !record.is_mesh() { + val box := record.made.shape.bounds(pose::identity); + extent = math::max(extent, (box.max - local).length); + extent = math::max(extent, (box.min - local).length); + val reach := record.made.shape.least_reach(); + least = least == 0 ? reach : math::min(least, reach); + } + c = record.next; + } + val i := b as u64; + this.bodies[i].mass = mass; + this.bodies[i].inv_mass = mass > 0 ? 1 / mass : 0f; + this.bodies[i].inertia = inertia; + this.bodies[i].inv_inertia = inverse; + this.bodies[i].local_center = local; + this.bodies[i].center = this.bodies[i].at.apply(local); + this.bodies[i].extent = extent; + this.bodies[i].least = least; +} + +# Puts a body's colliders' leaves where it is, each that leaves its grown box +# to find what it newly nears. +def space::place_colliders(&mut this, b: u32): void { + val at := this.bodies[b as u64].at; + var c := this.bodies[b as u64].colliders; + while c != none { + val box := this.box_of(c, at); + if this.tree.move(this.colliders[c as u64].leaf, box) && !this.colliders[c as u64].moved { + this.colliders[c as u64].moved = true; + this.moved.append(c); + } + c = this.colliders[c as u64].next; + } +} diff --git a/physics3d/step.sakura b/physics3d/step.sakura new file mode 100644 index 0000000..5bd8fb0 --- /dev/null +++ b/physics3d/step.sakura @@ -0,0 +1,76 @@ +#! Contains how a space steps forward in time, and what rays meet in it. + +import std::containers; +import std::math; +import std::time; +import malunal::geometry; +import malunal::linear; +module malunal::physics3d; + +#! Steps the space forward in time: finds what's newly near, where it meets, +#! and moves its bodies, pushed apart where they meet. Events of what began +#! and stopped touching are those of this step alone after. +pub def space::step(&mut this, dt: f32): void { + this.noted.clear(); + this.struck.clear(); + return if dt <= 0; + val began := instant::now(); + this.crew.start(this.threads); + this.find_pairs(); + val paired := instant::now(); + this.update_contacts(); + val met := instant::now(); + this.solve(dt); + val solved := instant::now(); + if this.sleeping { + this.sleep_islands(dt); + } + val slept := instant::now(); + this.profile = step_profile{ + pairs = milliseconds(paired - began), contacts = milliseconds(met - paired), + solve = milliseconds(solved - met), sleep = milliseconds(slept - solved), step = milliseconds(slept - began), + }; +} + +def milliseconds(d: duration): f64 { + return d.in_nanoseconds as f64 / 1e6; +} + +#! Where a ray met a space's collider: which, of which body, where, and of a +#! mesh's, which triangle. +pub struct space_hit { + pub var collider: collider_id; + pub var body: body_id; + pub var distance: f32; + pub var point: vec3; + pub var normal: vec3; + pub var triangle: u32 = 0xFFFFFFFF; +} + +#! Where a ray first meets a collider on a layer of a mask, sensors passed +#! over: from a place, along a direction of length 1, as far as `reach`. +pub def space::ray_cast(&this, origin: vec3, direction: vec3, reach: f32, mask: u32 = 0xFFFFFFFF): maybe { + return this.ray_cast(origin, direction, reach, query_filter{ mask = mask }); +} + +#! Where a ray first meets a collider a filter asks of, as `ray_cast` casts +#! it. +pub def space::ray_cast(&this, origin: vec3, direction: vec3, reach: f32, filter: query_filter): maybe { + var best: maybe = nothing{}; + this.tree.ray_cast(origin, direction, reach, def(leaf: u32, data: u64, so_far: f32): f32 { + val c := &this.colliders[data]; + return so_far if !this.passes(data as u32, &filter); + val at := this.bodies[c.body as u64].at; + val named := collider_id{ index = data as u32, generation = c.generation }; + val of := body_id{ index = c.body, generation = this.bodies[c.body as u64].generation }; + if c.is_mesh() { + val met := this.meshes[c.mesh as u64].ray_cast(at, origin, direction, so_far) else { return so_far; }; + best = space_hit{ collider = named, body = of, distance = met.distance, point = met.point, normal = met.normal, triangle = met.triangle }; + return met.distance; + } + val met := c.made.shape.ray_cast(at, origin, direction, so_far) else { return so_far; }; + best = space_hit{ collider = named, body = of, distance = met.distance, point = met.point, normal = met.normal }; + return met.distance; + }); + return best; +} diff --git a/physics3d/tree.sakura b/physics3d/tree.sakura new file mode 100644 index 0000000..92a3194 --- /dev/null +++ b/physics3d/tree.sakura @@ -0,0 +1,382 @@ +#! Contains `aabb_tree`, a tree of boxes: each leaf a box holding a number of +#! its user's, as an entity's bits, and each branch the least box holding its +#! two children, so what's near a box, or along a ray, is found by passing down +#! only the branches that reach it, as Box2D's dynamic tree finds it. +#! +#! A leaf's box is grown past what it holds by the tree's margin, so what moves +#! a little stays within it, and the tree isn't changed. A leaf is put where it +#! grows the area of the boxes above it least, and each branch it passes is +#! turned, as an AVL tree turns one, where one child is two or more deeper than +#! the other, so the tree stays shallow whatever order its leaves come in. + +import std::math; +import malunal::geometry; +import malunal::linear; +module malunal::physics3d; + +# No node. +const none_node: u32 = 0xFFFFFFFF; + +# The deepest a tree of shallow branches can be, with room to spare: past 2^40 +# leaves. +const most_depth: u64 = 64; + +struct tree_node { + var box: bounds; + var data: u64; + var parent: u32 = 0xFFFFFFFF; # Or the next free node, where it's free. + var left: u32 = 0xFFFFFFFF; # None of a leaf. + var right: u32 = 0xFFFFFFFF; + var height: i32; # 0 of a leaf, and -1 where it's free. +} + +#! A tree of boxes, each leaf holding a number of its user's, named by the leaf +#! `insert` gives, which stays its name until it's removed. +pub struct aabb_tree { + var nodes: vector; + var root: u32 = 0xFFFFFFFF; + var free: u32 = 0xFFFFFFFF; + var leaves: u64; + #! How far each leaf's box is grown past what it holds. + pub var margin: f32 = 0.1; +} + +#! A tree of no leaves, its boxes grown by a margin. +pub def aabb_tree::new(margin: f32 = 0.1): aabb_tree { + return aabb_tree{ nodes = vector::::new(), margin = margin }; +} + +#! How many leaves it holds. +pub val aabb_tree::length: u64 { + get => this.leaves; +} + +#! How deep it is: 0 of no leaves or one, and 1 more for each branch down to +#! its deepest leaf. +pub val aabb_tree::height: i32 { + get => this.root == none_node ? 0 : this.nodes[this.root as u64].height; +} + +#! Adds a box, and a number of the user's, as a leaf. +#! @returns The leaf, which names it until it's removed. +pub def aabb_tree::insert(&mut this, box: bounds, data: u64): u32 { + val leaf := this.allocate(); + this.nodes[leaf as u64].box = grown(box, this.margin); + this.nodes[leaf as u64].data = data; + this.nodes[leaf as u64].height = 0; + this.insert_leaf(leaf); + this.leaves++; + return leaf; +} + +#! Removes a leaf. +pub def aabb_tree::remove(&mut this, leaf: u32): void { + this.remove_leaf(leaf); + this.release(leaf); + this.leaves--; +} + +#! Moves a leaf to hold a box, where its grown box doesn't hold it already. +#! @returns Whether it was moved. +pub def aabb_tree::move(&mut this, leaf: u32, box: bounds): bool { + return false if this.nodes[leaf as u64].box.contains(box); + this.remove_leaf(leaf); + this.nodes[leaf as u64].box = grown(box, this.margin); + this.insert_leaf(leaf); + return true; +} + +#! The number a leaf holds. +pub def aabb_tree::data(&this, leaf: u32): u64 { + return this.nodes[leaf as u64].data; +} + +#! A leaf's box, grown by the margin. +pub def aabb_tree::box_of(&this, leaf: u32): bounds { + return this.nodes[leaf as u64].box; +} + +#! Visits each leaf whose box meets a box, as `visit(leaf, data)`, until it +#! gives false. +pub def aabb_tree::query(&this, box: bounds, visit: F): void where F: invokable { + return if this.root == none_node; + var stack: u32[64]; + var top: u64 = 1; + stack[0] = this.root; + while top > 0 { + top--; + val index := stack[top] as u64; + continue if !this.nodes[index].box.overlaps(box); + if this.nodes[index].left == none_node { + return if !visit(index as u32, this.nodes[index].data); + } else if top + 2 <= most_depth { + stack[top] = this.nodes[index].left; + stack[top + 1] = this.nodes[index].right; + top += 2; + } + } +} + +#! Visits each leaf whose box a ray meets, from a place, along a direction of +#! length 1, as far as `reach`, as `visit(leaf, data, reach)`, which gives how +#! far to go on: the distance of what it found there, so only what's nearer is +#! visited after; `reach` as it was, to go on as far; or 0, to stop. +pub def aabb_tree::ray_cast(&this, origin: vec3, direction: vec3, reach: f32, visit: F): void + where F: invokable { + return if this.root == none_node; + var far := reach; + var stack: u32[64]; + var top: u64 = 1; + stack[0] = this.root; + while top > 0 { + top--; + val index := stack[top] as u64; + continue if !ray_reaches(&this.nodes[index].box, origin, direction, far); + if this.nodes[index].left == none_node { + val next := visit(index as u32, this.nodes[index].data, far); + return if next <= 0; + far = math::min(far, next); + } else if top + 2 <= most_depth { + stack[top] = this.nodes[index].left; + stack[top + 1] = this.nodes[index].right; + top += 2; + } + } +} + +#! Whether the tree is as it should be: each node's parent its parent, each +#! branch's box the least holding its children's, and its height one more than +#! its deeper child's, each branch's children no more than one apart in height. +#! For tests. +pub def aabb_tree::is_sound(&this): bool { + return true if this.root == none_node; + return false if this.nodes[this.root as u64].parent != none_node; + var stack: u32[64]; + var top: u64 = 1; + var seen: u64 = 0; + stack[0] = this.root; + while top > 0 { + top--; + val index := stack[top] as u64; + val left := this.nodes[index].left; + val right := this.nodes[index].right; + if left == none_node { + return false if right != none_node || this.nodes[index].height != 0; + seen++; + continue; + } + val l := &this.nodes[left as u64]; + val r := &this.nodes[right as u64]; + return false if l.parent != index as u32 || r.parent != index as u32; + return false if this.nodes[index].height != 1 + math::max(l.height, r.height) || math::abs(l.height - r.height) > 1; + return false if !(l.box.merged(r.box) == this.nodes[index].box); + return false if top + 2 > most_depth; + stack[top] = left; + stack[top + 1] = right; + top += 2; + } + return seen == this.leaves; +} + +# A box grown so far each way. +def grown(box: bounds, by: f32): bounds { + val reach := vec3{ by, by, by }; + return bounds{ box.min - reach, box.max + reach }; +} + +# The area of a box's faces, which a tree weighs where to put a box by, as the +# chance a ray or a box passing by meets it. +def area_of(box: bounds): f32 { + val size := box.max - box.min; + return 2 * (size.x * size.y + size.y * size.z + size.z * size.x); +} + +# Whether a ray reaches a box, from a place, along a direction, as far as +# `reach`: whether it's between the box's faces along every axis at once. +def ray_reaches(box: &bounds, origin: vec3, direction: vec3, reach: f32): bool { + var low: f32 = 0; + var high := reach; + val origins: f32[3] = [origin.x, origin.y, origin.z]; + val ways: f32[3] = [direction.x, direction.y, direction.z]; + val lows: f32[3] = [box.min.x, box.min.y, box.min.z]; + val highs: f32[3] = [box.max.x, box.max.y, box.max.z]; + for i in 0..3u { + if math::abs(ways[i]) < tiny { + return false if origins[i] < lows[i] || origins[i] > highs[i]; + continue; + } + var near := (lows[i] - origins[i]) / ways[i]; + var far := (highs[i] - origins[i]) / ways[i]; + if near > far { + val swapped := near; + near = far; + far = swapped; + } + low = math::max(low, near); + high = math::min(high, far); + return false if low > high; + } + return true; +} + +# A node to use: a free one, or a new one. +def aabb_tree::allocate(&mut this): u32 { + if this.free == none_node { + this.nodes.append(tree_node{}); + return (this.nodes.length - 1) as u32; + } + val made := this.free; + this.free = this.nodes[made as u64].parent; + this.nodes[made as u64] = tree_node{}; + return made; +} + +# Frees a node, for another to use. +def aabb_tree::release(&mut this, index: u32): void { + this.nodes[index as u64] = tree_node{ parent = this.free, height = -1 }; + this.free = index; +} + +# What putting a box beneath a child costs: what the child's box grows by, or +# all of it, of a leaf, which a new branch takes the place of. +def aabb_tree::descent_cost(&this, child: u32, box: bounds): f32 { + val node := &this.nodes[child as u64]; + val merged := area_of(box.merged(node.box)); + return merged if node.left == none_node; + return merged - area_of(node.box); +} + +# Puts a leaf where it grows the boxes above it least: beside a node, beneath a +# new branch holding both. +def aabb_tree::insert_leaf(&mut this, leaf: u32): void { + if this.root == none_node { + this.root = leaf; + this.nodes[leaf as u64].parent = none_node; + return; + } + val box := this.nodes[leaf as u64].box; + var index := this.root; + while this.nodes[index as u64].left != none_node { + val node_box := this.nodes[index as u64].box; + val left := this.nodes[index as u64].left; + val right := this.nodes[index as u64].right; + val combined := area_of(node_box.merged(box)); + # Beside this node, a new branch holding both; beneath it, every box + # above grows as this one does. + val here := 2 * combined; + val inherited := 2 * (combined - area_of(node_box)); + val to_left := this.descent_cost(left, box) + inherited; + val to_right := this.descent_cost(right, box) + inherited; + break if here < to_left && here < to_right; + index = to_left < to_right ? left : right; + } + + val sibling := index; + val old_parent := this.nodes[sibling as u64].parent; + val branch := this.allocate(); + this.nodes[branch as u64].parent = old_parent; + this.nodes[branch as u64].box = box.merged(this.nodes[sibling as u64].box); + this.nodes[branch as u64].height = this.nodes[sibling as u64].height + 1; + this.nodes[branch as u64].left = sibling; + this.nodes[branch as u64].right = leaf; + this.nodes[sibling as u64].parent = branch; + this.nodes[leaf as u64].parent = branch; + if old_parent == none_node { + this.root = branch; + } else if this.nodes[old_parent as u64].left == sibling { + this.nodes[old_parent as u64].left = branch; + } else { + this.nodes[old_parent as u64].right = branch; + } + this.refit(this.nodes[leaf as u64].parent); +} + +# Takes a leaf out, its sibling taking its parent's place. +def aabb_tree::remove_leaf(&mut this, leaf: u32): void { + if leaf == this.root { + this.root = none_node; + return; + } + val parent := this.nodes[leaf as u64].parent; + val grandparent := this.nodes[parent as u64].parent; + val sibling := this.nodes[parent as u64].left == leaf ? this.nodes[parent as u64].right : this.nodes[parent as u64].left; + this.nodes[sibling as u64].parent = grandparent; + this.release(parent); + if grandparent == none_node { + this.root = sibling; + return; + } + if this.nodes[grandparent as u64].left == parent { + this.nodes[grandparent as u64].left = sibling; + } else { + this.nodes[grandparent as u64].right = sibling; + } + this.refit(grandparent); +} + +# Walks up from a branch to the root, turning each that's out of balance, and +# making its box and height those of its children again. +def aabb_tree::refit(&mut this, from: u32): void { + var index := from; + while index != none_node { + index = this.balance(index); + val left := this.nodes[index as u64].left; + val right := this.nodes[index as u64].right; + this.nodes[index as u64].height = 1 + math::max(this.nodes[left as u64].height, this.nodes[right as u64].height); + this.nodes[index as u64].box = this.nodes[left as u64].box.merged(this.nodes[right as u64].box); + index = this.nodes[index as u64].parent; + } +} + +# Turns a branch whose children are two or more apart in height: the deeper +# child takes its place, and it takes the deeper child's shallower child. +# @returns The node in its place now. +def aabb_tree::balance(&mut this, a: u32): u32 { + return a if this.nodes[a as u64].left == none_node || this.nodes[a as u64].height < 2; + val b := this.nodes[a as u64].left; + val c := this.nodes[a as u64].right; + val leaning := this.nodes[c as u64].height - this.nodes[b as u64].height; + if leaning > 1 { + this.raise(a, c, b, true); + return c; + } + if leaning < -1 { + this.raise(a, b, c, false); + return b; + } + return a; +} + +# Raises `up`, a child of `a`, into its place: `a` becomes `up`'s first child, +# beside `up`'s deeper child, and takes `up`'s shallower child where `up` was, +# `other` its child still. `on_right` says `up` was `a`'s right child. +def aabb_tree::raise(&mut this, a: u32, up: u32, other: u32, on_right: bool): void { + val f := this.nodes[up as u64].left; + val g := this.nodes[up as u64].right; + # `up` takes `a`'s place beneath its parent. + val above := this.nodes[a as u64].parent; + this.nodes[up as u64].left = a; + this.nodes[up as u64].parent = above; + this.nodes[a as u64].parent = up; + if above == none_node { + this.root = up; + } else if this.nodes[above as u64].left == a { + this.nodes[above as u64].left = up; + } else { + this.nodes[above as u64].right = up; + } + # `up` keeps its deeper child; `a` takes the shallower where `up` was. + val deeper := this.nodes[f as u64].height > this.nodes[g as u64].height ? f : g; + val shallower := deeper == f ? g : f; + this.nodes[up as u64].right = deeper; + if on_right { + this.nodes[a as u64].right = shallower; + } else { + this.nodes[a as u64].left = shallower; + } + this.nodes[shallower as u64].parent = a; + this.nodes[a as u64].box = this.nodes[other as u64].box.merged(this.nodes[shallower as u64].box); + this.nodes[a as u64].height = 1 + math::max(this.nodes[other as u64].height, this.nodes[shallower as u64].height); + this.nodes[up as u64].box = this.nodes[a as u64].box.merged(this.nodes[deeper as u64].box); + this.nodes[up as u64].height = 1 + math::max(this.nodes[a as u64].height, this.nodes[deeper as u64].height); +} diff --git a/physics3d/wide.sakura b/physics3d/wide.sakura new file mode 100644 index 0000000..6d27a38 --- /dev/null +++ b/physics3d/wide.sakura @@ -0,0 +1,544 @@ +#! Contains how a space solves its contacts eight at a time, as in a plane: +#! each step, every contact is given the first of 24 colors none of its dynamic +#! bodies has yet, so no two contacts of a color push the same body, and the +#! contacts of each color are solved as the lanes of `f32x8`s, eight at once, +#! each body's velocities gathered from where its state is and scattered back. +#! What fits no color is solved one at a time after. +#! +#! A body's inverse inertia, as it's turned as the step begins, is worked into +#! each point's levers as the contacts are packed, so the lanes turn a body by +#! what's packed, never a matrix of their own. + +import std::containers; +import std::math; +import malunal::linear; +module malunal::physics3d; + +# How many colors contacts are sorted into. +const colors: u64 = 24; + +# How many contacts are solved at once, and the vectors of their numbers. +const width: u64 = 8; +type lanes = f32x8; +type lane_places = i32x8; + +# How many numbers a body's state is: its velocities, how far it's moved, and +# how it's turned, each of four. +const state_numbers: u64 = 16; + +# A point of eight contacts, a lane each: where it is from each body's +# center, how far apart they are there but for how far they've moved, the +# impulses pushing them apart and along each tangent, how hard each is to push, +# and how each body turns by an impulse along each, its inverse inertia times +# its lever. A lane of a contact of fewer points has the rest of no mass, which +# push nothing. +struct wide_point { + var rax: lanes; + var ray: lanes; + var raz: lanes; + var rbx: lanes; + var rby: lanes; + var rbz: lanes; + var base: lanes; + var normal: lanes; + var tangent1: lanes; + var tangent2: lanes; + var most: lanes; + var mass_n: lanes; + var mass_1: lanes; + var mass_2: lanes; + var nax: lanes; + var nay: lanes; + var naz: lanes; + var nbx: lanes; + var nby: lanes; + var nbz: lanes; + var sax: lanes; # Along the first tangent. + var say: lanes; + var saz: lanes; + var sbx: lanes; + var sby: lanes; + var sbz: lanes; + var tax: lanes; # Along the second. + var tay: lanes; + var taz: lanes; + var tbx: lanes; + var tby: lanes; + var tbz: lanes; +} + +# Eight contacts as lanes: where each body's state begins among the states' +# numbers, the normal and tangents, friction, each body's inverse mass, and how +# soft each is. A lane of no contact is of the state of what doesn't move. +struct wide_contact { + var a: lane_places; + var b: lane_places; + var nx: lanes; + var ny: lanes; + var nz: lanes; + var t1x: lanes; + var t1y: lanes; + var t1z: lanes; + var t2x: lanes; + var t2y: lanes; + var t2z: lanes; + var friction: lanes; + var ma: lanes; + var mb: lanes; + var bias_rate: lanes; + var mass_scale: lanes; + var impulse_scale: lanes; + var points: wide_point[4]; + var of: u32[8]; # Each lane's constraint, or none. +} + +# The states' numbers, sixteen to a state, as `wide_contact`'s lanes gather +# them. +def numbers_of(s: &mut solver_scratch): slice { + return slice::::over(s.states.data as *mut f32, s.states.length * state_numbers); +} + +# Sorts the step's contacts into colors, and packs each color's into lanes. +def color_contacts(s: &mut solver_scratch): void { + s.wide.clear(); + s.overflow.clear(); + val words := (s.states.length + 63) / 64; + s.colored.clear(); + s.colored.resize(colors * words, 0); + s.color_of.clear(); + s.color_of.resize(s.constraints.length, none); + var counts: u32[24]; + for k in 0..s.constraints.length { + val c := &s.constraints[k]; + # Only a body that's pushed is a body two lanes mustn't share. + val a := c.ma > 0 ? c.a as u64 : 0u; + val b := c.mb > 0 ? c.b as u64 : 0u; + for color in 0..colors { + val row := color * words; + continue if a != 0 && ((s.colored[row + a / 64] >> (a % 64)) & 1) != 0; + continue if b != 0 && ((s.colored[row + b / 64] >> (b % 64)) & 1) != 0; + if a != 0 { + s.colored[row + a / 64] = s.colored[row + a / 64] | (1u << (a % 64)); + } + if b != 0 { + s.colored[row + b / 64] = s.colored[row + b / 64] | (1u << (b % 64)); + } + s.color_of[k] = color as u32; + counts[color]++; + break; + } + if s.color_of[k] == none { + s.overflow.append(k as u32); + } + } + var first: u32[24]; + var groups: u64 = 0; + for color in 0..colors { + first[color] = groups as u32; + s.color_groups[color] = groups as u32; + groups += (counts[color] as u64 + width - 1) / width; + } + s.color_groups[colors] = groups as u32; + s.wide.resize(groups, wide_contact{}); + for g in 0..groups { + for lane in 0..width { + s.wide[g].of[lane] = none; + } + } + var filled: u32[24]; + for k in 0..s.constraints.length { + val color := s.color_of[k]; + continue if color == none; + val at := filled[color as u64]; + filled[color as u64]++; + val c := &s.constraints[k]; + pack(&mut s.wide[(first[color as u64] as u64 + at as u64 / width)], at as u64 % width, c, k as u32, s.inertias[c.a as u64], s.inertias[c.b as u64]); + } +} + +# Puts a contact into a lane. +def pack(w: &mut wide_contact, lane: u64, c: &contact_constraint, k: u32, ia: mat3, ib: mat3): void { + w.of[lane] = k; + w.a[lane] = (c.a as u64 * state_numbers) as i32; + w.b[lane] = (c.b as u64 * state_numbers) as i32; + w.nx[lane] = c.normal.x; + w.ny[lane] = c.normal.y; + w.nz[lane] = c.normal.z; + w.t1x[lane] = c.t1.x; + w.t1y[lane] = c.t1.y; + w.t1z[lane] = c.t1.z; + w.t2x[lane] = c.t2.x; + w.t2y[lane] = c.t2.y; + w.t2z[lane] = c.t2.z; + w.friction[lane] = c.friction; + w.ma[lane] = c.ma; + w.mb[lane] = c.mb; + w.bias_rate[lane] = c.soft.bias_rate; + w.mass_scale[lane] = c.soft.mass_scale; + w.impulse_scale[lane] = c.soft.impulse_scale; + for j in 0..c.count { + val p := &c.points[j]; + val q := &mut w.points[j]; + val ra := p.anchor_a; + val rb := p.anchor_b; + q.rax[lane] = ra.x; + q.ray[lane] = ra.y; + q.raz[lane] = ra.z; + q.rbx[lane] = rb.x; + q.rby[lane] = rb.y; + q.rbz[lane] = rb.z; + q.base[lane] = p.base_separation; + q.normal[lane] = p.normal_impulse; + q.tangent1[lane] = p.tangent_impulse.x; + q.tangent2[lane] = p.tangent_impulse.y; + q.mass_n[lane] = p.normal_mass; + q.mass_1[lane] = p.tangent_mass.x; + q.mass_2[lane] = p.tangent_mass.y; + val na := ia * ra.cross(c.normal); + val nb := ib * rb.cross(c.normal); + val sa := ia * ra.cross(c.t1); + val sb := ib * rb.cross(c.t1); + val ta := ia * ra.cross(c.t2); + val tb := ib * rb.cross(c.t2); + q.nax[lane] = na.x; + q.nay[lane] = na.y; + q.naz[lane] = na.z; + q.nbx[lane] = nb.x; + q.nby[lane] = nb.y; + q.nbz[lane] = nb.z; + q.sax[lane] = sa.x; + q.say[lane] = sa.y; + q.saz[lane] = sa.z; + q.sbx[lane] = sb.x; + q.sby[lane] = sb.y; + q.sbz[lane] = sb.z; + q.tax[lane] = ta.x; + q.tay[lane] = ta.y; + q.taz[lane] = ta.z; + q.tbx[lane] = tb.x; + q.tby[lane] = tb.y; + q.tbz[lane] = tb.z; + } +} + +# Gives each lane's impulses back to its contact, to bounce and keep. +def unpack_contacts(s: &mut solver_scratch): void { + for g in 0..s.wide.length { + for lane in 0..width { + val k := s.wide[g].of[lane]; + continue if k == none; + for j in 0..s.constraints[k as u64].count { + val q := &s.wide[g].points[j]; + val p := &mut s.constraints[k as u64].points[j]; + p.normal_impulse = q.normal[lane]; + p.tangent_impulse = vec3{ q.tangent1[lane], q.tangent2[lane], 0 }; + p.max_impulse = math::max(p.max_impulse, q.most[lane]); + } + } + } +} + +# Which lanes push a body, by its inverse mass: those of what doesn't move, or +# isn't pushed, as a kinematic body, aren't written back, as lanes on other +# threads read its state. +def pushed(m: lanes): bool[8] { + val ms := m.lanes(); + var made: bool[8]; + for k in 0..width { + made[k] = ms[k] > 0; + } + return made; +} +# Each lane's square root, a lane at a time. +def root_of(x: lanes): lanes { + var each := x.lanes(); + for i in 0..width { + each[i] = math::sqrt(each[i]); + } + return lanes::of(each); +} + +# A stage of a step's lanes, run on the space's crew a color at a time: the +# lanes of each color split between its threads, as no two lanes of a color +# push one body. +struct wide_job { + var s: *mut solver_scratch; + var first: u64; + var warming: bool; + var inv_h: f32; + var push: f32; + var use_bias: bool; +} + +def run_wide(context: *mut u8, begin: u64, end: u64): void { + val job := &through(context as *mut wide_job); + val s := &mut through(job.s); + if job.warming { + warm_groups(s, job.first + begin, job.first + end); + } else { + solve_groups(s, job.first + begin, job.first + end, job.inv_h, job.push, job.use_bias); + } +} + +# Warms or solves the lanes, on the crew where the space has one, a color at a +# time. +def space::wide_stage(&mut this, s: &mut solver_scratch, warming: bool, inv_h: f32, push: f32, use_bias: bool): void { + if this.threads <= 1 { + if warming { + warm_groups(s, 0, s.wide.length); + } else { + solve_groups(s, 0, s.wide.length, inv_h, push, use_bias); + } + return; + } + var job := wide_job{ s = address(s), warming = warming, inv_h = inv_h, push = push, use_bias = use_bias }; + for color in 0..colors { + val from := s.color_groups[color] as u64; + val to := s.color_groups[color + 1] as u64; + continue if to == from; + job.first = from; + val block := math::max((to - from) / (this.threads as u64 * 4), 1u); + this.crew.run(run_wide, address(&mut job) as *mut u8, to - from, block); + } +} + +# Writes each pushed lane's number back to where it was gathered from. +def put(v: lanes, into: slice, at: lane_places, keep: &bool[8]): void { + val each := v.lanes(); + val places := at.lanes(); + for k in 0..width { + if keep[k] { + into[places[k] as u64] = each[k]; + } + } +} +def warm_groups(s: &mut solver_scratch, from: u64, to: u64): void { + val numbers := numbers_of(s); + val view := numbers.span; + val one := lane_places::splat(1); + val two := lane_places::splat(2); + val four := lane_places::splat(4); + val five := lane_places::splat(5); + val six := lane_places::splat(6); + val groups := s.wide.slice; + for g in from..to { + val w := &groups[g]; + val keep_a := pushed(w.ma); + val keep_b := pushed(w.mb); + var vax := lanes::gather(view, w.a); + var vay := lanes::gather(view, w.a + one); + var vaz := lanes::gather(view, w.a + two); + var wax := lanes::gather(view, w.a + four); + var way := lanes::gather(view, w.a + five); + var waz := lanes::gather(view, w.a + six); + var vbx := lanes::gather(view, w.b); + var vby := lanes::gather(view, w.b + one); + var vbz := lanes::gather(view, w.b + two); + var wbx := lanes::gather(view, w.b + four); + var wby := lanes::gather(view, w.b + five); + var wbz := lanes::gather(view, w.b + six); + for j in 0..4u { + val p := &w.points[j]; + val n := p.normal; + val t1 := p.tangent1; + val t2 := p.tangent2; + val px := w.nx * n + w.t1x * t1 + w.t2x * t2; + val py := w.ny * n + w.t1y * t1 + w.t2y * t2; + val pz := w.nz * n + w.t1z * t1 + w.t2z * t2; + vax = vax - px * w.ma; + vay = vay - py * w.ma; + vaz = vaz - pz * w.ma; + vbx = vbx + px * w.mb; + vby = vby + py * w.mb; + vbz = vbz + pz * w.mb; + wax = wax - (p.nax * n + p.sax * t1 + p.tax * t2); + way = way - (p.nay * n + p.say * t1 + p.tay * t2); + waz = waz - (p.naz * n + p.saz * t1 + p.taz * t2); + wbx = wbx + (p.nbx * n + p.sbx * t1 + p.tbx * t2); + wby = wby + (p.nby * n + p.sby * t1 + p.tby * t2); + wbz = wbz + (p.nbz * n + p.sbz * t1 + p.tbz * t2); + } + put(vax, numbers, w.a, &keep_a); + put(vay, numbers, w.a + one, &keep_a); + put(vaz, numbers, w.a + two, &keep_a); + put(wax, numbers, w.a + four, &keep_a); + put(way, numbers, w.a + five, &keep_a); + put(waz, numbers, w.a + six, &keep_a); + put(vbx, numbers, w.b, &keep_b); + put(vby, numbers, w.b + one, &keep_b); + put(vbz, numbers, w.b + two, &keep_b); + put(wbx, numbers, w.b + four, &keep_b); + put(wby, numbers, w.b + five, &keep_b); + put(wbz, numbers, w.b + six, &keep_b); + } +} + +def solve_groups(s: &mut solver_scratch, from: u64, to: u64, inv_h: f32, push: f32, use_bias: bool): void { + val numbers := numbers_of(s); + val view := numbers.span; + val one := lane_places::splat(1); + val two := lane_places::splat(2); + val four := lane_places::splat(4); + val five := lane_places::splat(5); + val six := lane_places::splat(6); + val eight := lane_places::splat(8); + val nine := lane_places::splat(9); + val ten := lane_places::splat(10); + val twelve := lane_places::splat(12); + val thirteen := lane_places::splat(13); + val fourteen := lane_places::splat(14); + val fifteen := lane_places::splat(15); + val zero := lanes::splat(0); + val unit := lanes::splat(1); + val doubled := lanes::splat(2); + val per_h := lanes::splat(inv_h); + val least := lanes::splat(-push); + val groups := s.wide.slice; + for g in from..to { + val w := &mut groups[g]; + val keep_a := pushed(w.ma); + val keep_b := pushed(w.mb); + var vax := lanes::gather(view, w.a); + var vay := lanes::gather(view, w.a + one); + var vaz := lanes::gather(view, w.a + two); + var wax := lanes::gather(view, w.a + four); + var way := lanes::gather(view, w.a + five); + var waz := lanes::gather(view, w.a + six); + var vbx := lanes::gather(view, w.b); + var vby := lanes::gather(view, w.b + one); + var vbz := lanes::gather(view, w.b + two); + var wbx := lanes::gather(view, w.b + four); + var wby := lanes::gather(view, w.b + five); + var wbz := lanes::gather(view, w.b + six); + val dpx := lanes::gather(view, w.b + eight) - lanes::gather(view, w.a + eight); + val dpy := lanes::gather(view, w.b + nine) - lanes::gather(view, w.a + nine); + val dpz := lanes::gather(view, w.b + ten) - lanes::gather(view, w.a + ten); + val qax := lanes::gather(view, w.a + twelve); + val qay := lanes::gather(view, w.a + thirteen); + val qaz := lanes::gather(view, w.a + fourteen); + val qaw := lanes::gather(view, w.a + fifteen); + val qbx := lanes::gather(view, w.b + twelve); + val qby := lanes::gather(view, w.b + thirteen); + val qbz := lanes::gather(view, w.b + fourteen); + val qbw := lanes::gather(view, w.b + fifteen); + val nx := w.nx; + val ny := w.ny; + val nz := w.nz; + val ma := w.ma; + val mb := w.mb; + for j in 0..4u { + val p := &mut w.points[j]; + val rax := p.rax; + val ray := p.ray; + val raz := p.raz; + val rbx := p.rbx; + val rby := p.rby; + val rbz := p.rbz; + # Each anchor as its body has turned since the step began: r + w·t + + # q × t, of t = 2 q × r. + val tax := doubled * (qay * raz - qaz * ray); + val tay := doubled * (qaz * rax - qax * raz); + val taz := doubled * (qax * ray - qay * rax); + val tbx := doubled * (qby * rbz - qbz * rby); + val tby := doubled * (qbz * rbx - qbx * rbz); + val tbz := doubled * (qbx * rby - qby * rbx); + val dx := dpx + (rbx + qbw * tbx + (qby * tbz - qbz * tby)) - (rax + qaw * tax + (qay * taz - qaz * tay)); + val dy := dpy + (rby + qbw * tby + (qbz * tbx - qbx * tbz)) - (ray + qaw * tay + (qaz * tax - qax * taz)); + val dz := dpz + (rbz + qbw * tbz + (qbx * tby - qby * tbx)) - (raz + qaw * taz + (qax * tay - qay * tax)); + val separation := dx * nx + dy * ny + dz * nz + p.base; + val apart := separation.greater(&zero); + var bias := select(apart, separation * per_h, zero); + var mass_scale := unit; + var impulse_scale := zero; + if use_bias { + bias = select(apart, bias, (w.bias_rate * separation).max(&least)); + mass_scale = select(apart, unit, w.mass_scale); + impulse_scale = select(apart, zero, w.impulse_scale); + } + # How fast they close: along the normal, and as each turns about its + # lever across it. + val vn := (vbx - vax) * nx + (vby - vay) * ny + (vbz - vaz) * nz + + wbx * (rby * nz - rbz * ny) + wby * (rbz * nx - rbx * nz) + wbz * (rbx * ny - rby * nx) + - wax * (ray * nz - raz * ny) - way * (raz * nx - rax * nz) - waz * (rax * ny - ray * nx); + val before := p.normal; + val sum := (before - p.mass_n * mass_scale * (vn + bias) - impulse_scale * before).max(&zero); + val impulse := sum - before; + p.normal = sum; + p.most = p.most.max(&impulse); + vax = vax - nx * impulse * ma; + vay = vay - ny * impulse * ma; + vaz = vaz - nz * impulse * ma; + vbx = vbx + nx * impulse * mb; + vby = vby + ny * impulse * mb; + vbz = vbz + nz * impulse * mb; + wax = wax - p.nax * impulse; + way = way - p.nay * impulse; + waz = waz - p.naz * impulse; + wbx = wbx + p.nbx * impulse; + wby = wby + p.nby * impulse; + wbz = wbz + p.nbz * impulse; + } + # Friction along both tangents, of no more in all than its share of what + # pushes them apart. + val t1x := w.t1x; + val t1y := w.t1y; + val t1z := w.t1z; + val t2x := w.t2x; + val t2y := w.t2y; + val t2z := w.t2z; + for j in 0..4u { + val p := &mut w.points[j]; + val rax := p.rax; + val ray := p.ray; + val raz := p.raz; + val rbx := p.rbx; + val rby := p.rby; + val rbz := p.rbz; + val dvx := vbx + (wby * rbz - wbz * rby) - vax - (way * raz - waz * ray); + val dvy := vby + (wbz * rbx - wbx * rbz) - vay - (waz * rax - wax * raz); + val dvz := vbz + (wbx * rby - wby * rbx) - vaz - (wax * ray - way * rax); + val before1 := p.tangent1; + val before2 := p.tangent2; + var sum1 := before1 - p.mass_1 * (dvx * t1x + dvy * t1y + dvz * t1z); + var sum2 := before2 - p.mass_2 * (dvx * t2x + dvy * t2y + dvz * t2z); + val most := w.friction * p.normal; + val squared := sum1 * sum1 + sum2 * sum2; + val most_squared := most * most; + val over := squared.greater(&most_squared); + val scale := select(over, most / root_of(select(over, squared, unit)), unit); + sum1 = sum1 * scale; + sum2 = sum2 * scale; + p.tangent1 = sum1; + p.tangent2 = sum2; + val d1 := sum1 - before1; + val d2 := sum2 - before2; + val px := t1x * d1 + t2x * d2; + val py := t1y * d1 + t2y * d2; + val pz := t1z * d1 + t2z * d2; + vax = vax - px * ma; + vay = vay - py * ma; + vaz = vaz - pz * ma; + vbx = vbx + px * mb; + vby = vby + py * mb; + vbz = vbz + pz * mb; + wax = wax - (p.sax * d1 + p.tax * d2); + way = way - (p.say * d1 + p.tay * d2); + waz = waz - (p.saz * d1 + p.taz * d2); + wbx = wbx + (p.sbx * d1 + p.tbx * d2); + wby = wby + (p.sby * d1 + p.tby * d2); + wbz = wbz + (p.sbz * d1 + p.tbz * d2); + } + put(vax, numbers, w.a, &keep_a); + put(vay, numbers, w.a + one, &keep_a); + put(vaz, numbers, w.a + two, &keep_a); + put(wax, numbers, w.a + four, &keep_a); + put(way, numbers, w.a + five, &keep_a); + put(waz, numbers, w.a + six, &keep_a); + put(vbx, numbers, w.b, &keep_b); + put(vby, numbers, w.b + one, &keep_b); + put(vbz, numbers, w.b + two, &keep_b); + put(wbx, numbers, w.b + four, &keep_b); + put(wby, numbers, w.b + five, &keep_b); + put(wbz, numbers, w.b + six, &keep_b); + } +} diff --git a/tests/character2d.sakura b/tests/character2d.sakura new file mode 100644 index 0000000..d1773d9 --- /dev/null +++ b/tests/character2d.sakura @@ -0,0 +1,131 @@ +#! Contains the tests of `physics2d`'s characters: walking ground, stepping up +#! a stair but not a wall, walking up a gentle slope but not a steep one, +#! riding a moving platform, jumping up through a one-way platform and landing +#! on it, and walking a chain of segments. + +import std::testing; +import std::containers; +import std::math; +import malunal::linear; +import malunal::physics2d; + +def about(a: f32, b: f32, within: f32): bool { + return math::abs(a - b) <= within; +} + +def standing(s: &mut space, at: vec2): character { + val floor := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, -1 }) }); + _ = s.attach(floor, collider{ shape = shape::box(vec2{ 50, 1 }) }); + var c := character{ at = at }; + s.move_character(&mut c, vec2::zero, 1f / 60f); + return c; +} + +# Walks a character for a time, falling where it's in the air, jumping at +# first where it's asked. +def walk(s: &mut space, c: &mut character, along: f32, seconds: f32, jump: f32 = 0): void { + val n := (seconds * 60) as u32; + for i in 0..n { + var v := c.velocity; + v.x = along; + if !c.grounded { + v.y -= 10f / 60f; + } else if i == 0 && jump > 0 { + v.y = jump; + } + s.move_character(c, v, 1f / 60f); + s.step(1f / 60f); + } +} + +def block(s: &mut space, center: vec2, half: vec2, angle: f32 = 0): void { + val made := s.add(body{ kind = body_kind::static, at = pose::of(center, angle) }); + _ = s.attach(made, collider{ shape = shape::box(half) }); +} + +@test def walks_and_steps(t: &mut tester): void { + var s := space::new(); + var c := standing(&mut s, vec2{ 0, 1 }); + walk(&mut s, &mut c, 0, 0.5); + t.expects(c.grounded && about(c.at.y, 0.92, 0.01)); + block(&mut s, vec2{ 3, 0.125 }, vec2{ 1, 0.125 }); + block(&mut s, vec2{ 8, 0.3 }, vec2{ 1, 0.3 }); + walk(&mut s, &mut c, 2, 4); + t.expects(c.grounded && about(c.at.x, 7 - 0.3 - 0.02, 0.05) && about(c.at.y, 0.92, 0.02)); +} + +@test def walks_around_a_world(t: &mut tester): void { + # A world of 20 meters, up away from its middle wherever the character is. + var s := space::new(vec2::zero); + val world := s.add(body{ kind = body_kind::static }); + _ = s.attach(world, collider{ shape = shape::circle(20) }); + var c := character{ at = vec2{ 0, 21 } }; + # Walking at 3 meters a second along the ground, clockwise around the + # world's middle, falling toward it where it's in the air, and on the + # ground keeping nothing of how fast it moved up. + for i in 0..600u { + c.up = c.at.normalized(); + var v := vec2{ c.up.y, -c.up.x } * 3; + if !c.grounded { + v = v + c.up * (c.velocity.dot(c.up) - 10f / 60f); + } + s.move_character(&mut c, v, 1f / 60f); + s.step(1f / 60f); + } + # It stands on the ground, as far from the middle as its feet put it, 30 + # meters around from where it began, its shape standing along its up. + val around := math::pi as f32 / 2 - math::atan2(c.at.y, c.at.x); + t.expects(c.grounded && about(c.at.length, 20.92, 0.01) && about(around, 30f / 20.92f, 0.05)); + t.expects(c.ground_normal.dot(c.up) > 0.99 && (c.pose().turn.apply(vec2{ 0, 1 }) - c.up).length < 0.001); +} + +@test def walks_gentle_slopes_but_not_steep_ones(t: &mut tester): void { + var s := space::new(); + var c := standing(&mut s, vec2{ 0, 0.92 }); + block(&mut s, vec2{ 1, 0 } + rot::of(0.35).apply(vec2{ 4, -0.5 }), vec2{ 4, 0.5 }, 0.35); + walk(&mut s, &mut c, 2, 2); + t.expects(c.grounded && c.at.y > 1.5); + var steep := space::new(); + var d := standing(&mut steep, vec2{ 0, 0.92 }); + block(&mut steep, vec2{ 1, 0 } + rot::of(1.1).apply(vec2{ 4, -0.5 }), vec2{ 4, 0.5 }, 1.1); + walk(&mut steep, &mut d, 2, 2); + t.expects(d.at.y < 1.3 && d.at.x < 1.5); +} + +@test def rides_moving_platforms(t: &mut tester): void { + var s := space::new(); + var c := standing(&mut s, vec2{ 0, 0.92 }); + val lift := s.add(body{ kind = body_kind::kinematic, at = pose::of(vec2{ 0, 0.25 }) }); + _ = s.attach(lift, collider{ shape = shape::box(vec2{ 1, 0.1 }) }); + c.at = vec2{ 0, 0.35 + 0.92 }; + s.move_character(&mut c, vec2::zero, 1f / 60f); + s.set_velocity(lift, vec2{ 1, 0.5 }); + walk(&mut s, &mut c, 0, 2); + t.expects(c.grounded && about(c.at.x, s.pose_of(lift).at.x, 0.1) && about(c.at.y, s.pose_of(lift).at.y + 0.1 + 0.92, 0.03)); +} + +@test def jumps_up_through_one_way_platforms(t: &mut tester): void { + var s := space::new(); + var c := standing(&mut s, vec2{ 0, 0.92 }); + val ledge := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, 2 }) }); + _ = s.attach(ledge, collider{ shape = shape::box(vec2{ 2, 0.1 }), one_way = true }); + walk(&mut s, &mut c, 0, 2, 9); + t.expects(c.grounded && about(c.at.y, 2.1 + 0.92, 0.02)); +} + +@test def walks_chains(t: &mut tester): void { + var s := space::new(); + # Ground of a chain, bumpy but gentle, right to left so it faces up. + var places := vector::::new(); + var i: i64 = 40; + while i >= 0 { + places.append(vec2{ i as f32 * 0.5 - 2, i % 2 == 0 ? 0f : 0.05f }); + i--; + } + val ground := s.add(body{ kind = body_kind::static }); + _ = s.attach_chain(ground, places.span, false, collider{}); + var c := character{ at = vec2{ 0, 1 } }; + walk(&mut s, &mut c, 0, 0.5); + walk(&mut s, &mut c, 3, 3); + t.expects(c.grounded && about(c.at.x, 9, 0.2) && c.at.y > 0.9 && c.at.y < 1); +} diff --git a/tests/character3d.sakura b/tests/character3d.sakura new file mode 100644 index 0000000..3bc8552 --- /dev/null +++ b/tests/character3d.sakura @@ -0,0 +1,151 @@ +#! Contains the tests of `physics3d`'s characters: walking a floor, stepping up +#! a stair but not a wall, walking up a gentle ramp but not a steep one, +#! sliding along a wall, riding a moving platform, pushed by what moves into +#! it, and pushing a crate. + +import std::testing; +import std::math; +import malunal::linear; +import malunal::physics3d; + +def about(a: f32, b: f32, within: f32): bool { + return math::abs(a - b) <= within; +} + +# A space with a floor, its top at y 0, and a character standing on it. +def standing(s: &mut space, at: vec3): character { + val floor := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ 0, -1, 0 }) }); + _ = s.attach(floor, collider{ shape = shape::box(vec3{ 50, 1, 50 }) }); + var c := character{ at = at }; + s.move_character(&mut c, vec3::zero, 1f / 60f); + return c; +} + +# Walks a character at a velocity across the ground for a time, falling where +# it's in the air, the space stepped beside it. +def walk(s: &mut space, c: &mut character, along: vec3, seconds: f32): void { + val n := (seconds * 60) as u32; + for i in 0..n { + var v := c.velocity; + v.x = along.x; + v.z = along.z; + if !c.grounded { + v.y -= 10f / 60f; + } + + + s.move_character(c, v, 1f / 60f); + s.step(1f / 60f); + + } +} + +def block(s: &mut space, center: vec3, half: vec3, turn: quat = quat::identity): body_id { + val made := s.add(body{ kind = body_kind::static, at = pose::of(center, turn) }); + _ = s.attach(made, collider{ shape = shape::box(half) }); + return made; +} + +@test def walks_floors(t: &mut tester): void { + var s := space::new(); + var c := standing(&mut s, vec3{ 0, 1, 0 }); + walk(&mut s, &mut c, vec3{ 2, 0, 0 }, 0.5); + # It fell to the floor, stands on it, and walks across it. + t.expects(c.grounded && about(c.at.y, 0.92, 0.01)); + walk(&mut s, &mut c, vec3{ 2, 0, 0 }, 2); + t.expects(c.grounded && about(c.at.x, 5, 0.1) && about(c.at.y, 0.92, 0.01)); +} + +@test def steps_up_stairs_but_not_walls(t: &mut tester): void { + var s := space::new(); + var c := standing(&mut s, vec3{ 0, 0.92, 0 }); + _ = block(&mut s, vec3{ 3, 0.15, 0 }, vec3{ 1, 0.15, 2 }); + _ = block(&mut s, vec3{ 8, 0.3, 0 }, vec3{ 1, 0.3, 2 }); + walk(&mut s, &mut c, vec3{ 2, 0, 0 }, 4); + # Up the stair 30 centimeters high, onto it and off it, then stopped by the + # block 60 centimeters high. + t.expects(c.grounded && about(c.at.x, 7 - 0.3 - 0.02, 0.05) && about(c.at.y, 0.92, 0.02)); +} + +@test def walks_up_gentle_ramps_but_not_steep_ones(t: &mut tester): void { + var s := space::new(); + var c := standing(&mut s, vec3{ 0, 0.92, 0 }); + # A ramp of 20 degrees rising toward +x, from x 1. + val gentle := quat::axis_angle(vec3::back, 0.35); + _ = block(&mut s, vec3{ 1, 0, 0 } + gentle * vec3{ 4, -0.5, 0 }, vec3{ 4, 0.5, 2 }, gentle); + walk(&mut s, &mut c, vec3{ 2, 0, 0 }, 2); + t.expects(c.grounded && c.at.y > 1.5); + var steep_space := space::new(); + var d := standing(&mut steep_space, vec3{ 0, 0.92, 0 }); + val steep := quat::axis_angle(vec3::back, 1.1); + _ = block(&mut steep_space, vec3{ 1, 0, 0 } + steep * vec3{ 4, -0.5, 0 }, vec3{ 4, 0.5, 2 }, steep); + walk(&mut steep_space, &mut d, vec3{ 2, 0, 0 }, 2); + t.expects(d.at.y < 1.3 && d.at.x < 1.5); +} + +@test def slides_along_walls(t: &mut tester): void { + var s := space::new(); + var c := standing(&mut s, vec3{ 0, 0.92, 0 }); + _ = block(&mut s, vec3{ 2, 1, 0 }, vec3{ 0.5, 1, 20 }); + # Walking into the wall at 45 degrees, it slides along it. + walk(&mut s, &mut c, vec3{ 2, 0, 2 }, 2); + t.expects(about(c.at.x, 1.5 - 0.3 - 0.02, 0.03) && c.at.z > 3); +} + +@test def rides_platforms_and_is_pushed(t: &mut tester): void { + var s := space::new(); + var c := standing(&mut s, vec3{ 0, 0.92, 0 }); + val lift := s.add(body{ kind = body_kind::kinematic, at = pose::of(vec3{ 0, 0.25, 0 }) }); + _ = s.attach(lift, collider{ shape = shape::box(vec3{ 1, 0.1, 1 }) }); + c.at = vec3{ 0, 0.35 + 0.92, 0 }; + s.move_character(&mut c, vec3::zero, 1f / 60f); + s.set_velocity(lift, vec3{ 1, 0, 0 }); + walk(&mut s, &mut c, vec3::zero, 2); + # Carried along by the platform it stands on. + t.expects(c.grounded && about(c.at.x, s.pose_of(lift).at.x, 0.1) && about(s.pose_of(lift).at.x, 2, 0.05)); + # A wall moving into it pushes it along. + var w := space::new(); + var d := standing(&mut w, vec3{ 0, 0.92, 0 }); + val pusher := w.add(body{ kind = body_kind::kinematic, at = pose::of(vec3{ -2, 1, 0 }) }); + _ = w.attach(pusher, collider{ shape = shape::box(vec3{ 0.5, 1, 2 }) }); + w.set_velocity(pusher, vec3{ 1, 0, 0 }); + walk(&mut w, &mut d, vec3::zero, 3); + t.expects(d.at.x > 0.5 && d.at.x > w.pose_of(pusher).at.x + 0.5 + 0.25); +} + +@test def walks_around_a_world(t: &mut tester): void { + # A world of 20 meters, up away from its middle wherever the character is. + var s := space::new(vec3::zero); + val world := s.add(body{ kind = body_kind::static }); + _ = s.attach(world, collider{ shape = shape::sphere(20) }); + var c := character{ at = vec3{ 0, 21, 0 } }; + # Walking at 3 meters a second along the ground, around the world's middle + # toward +x, falling toward it where it's in the air. Up turns as it walks, + # so what was along the ground a step ago leans up from it: on the ground, + # it keeps nothing of how fast it moved up. + for i in 0..600u { + c.up = c.at.normalized(); + var v := c.up.cross(vec3::back).normalized() * 3; + if !c.grounded { + v = v + c.up * (c.velocity.dot(c.up) - 10f / 60f); + } + s.move_character(&mut c, v, 1f / 60f); + s.step(1f / 60f); + } + # It stands on the ground, as far from the middle as its feet put it, 30 + # meters around from where it began: its shape stood along its up all along. + val around := math::pi as f32 / 2 - math::atan2(c.at.y, c.at.x); + t.expects(c.grounded && about(c.at.length, 20.92, 0.01) && about(around, 30f / 20.92f, 0.05)); + t.expects(c.ground_normal.dot(c.up) > 0.99 && about(c.at.z, 0, 0.01)); + # Its pose stands its shape along its up. + t.expects((c.pose().turn * vec3::up - c.up).length < 0.001); +} + +@test def pushes_crates(t: &mut tester): void { + var s := space::new(); + var c := standing(&mut s, vec3{ 0, 0.92, 0 }); + val crate := s.add(body{ at = pose::of(vec3{ 1.5, 0.5, 0 }) }); + _ = s.attach(crate, collider{ shape = shape::box(vec3{ 0.5, 0.5, 0.5 }), density = 20 }); + walk(&mut s, &mut c, vec3{ 1.5, 0, 0 }, 3); + t.expects(s.pose_of(crate).at.x > 3 && c.at.x < s.pose_of(crate).at.x); +} diff --git a/tests/geometry.sakura b/tests/geometry.sakura new file mode 100644 index 0000000..a872e00 --- /dev/null +++ b/tests/geometry.sakura @@ -0,0 +1,178 @@ +#! Contains the tests of `geometry`: planes, and which side of one something +#! lies on; boxes and spheres holding places and meeting; rays meeting each +#! shape; a camera's frustum reaching what it sees; and the same bits whether +#! numbers are worked as lanes or one at a time, which `malunal.geometry.tests` +#! and `malunal.geometry.lanes.tests` each check. + +import std::testing; +import std::json; +import std::math; +import malunal::linear; +import malunal::geometry; + +# Whether two numbers are within a millionth or so of one another. +def near(a: f32, b: f32): bool { + return math::abs(a - b) < 1e-5; +} + +def near(a: vec3, b: vec3): bool { + return near(a.x, b.x) && near(a.y, b.y) && near(a.z, b.z); +} + +# How far along a ray it meets a shape, or -1 where it doesn't. +def hit_at(found: maybe): f32 { + return found is some(t) ? t : -1; +} + +@test def lays_out_its_shapes(t: &mut tester): void { + t.expects(size_of::() == 32 && size_of::() == 20 && size_of::() == 32 && size_of::() == 20); + t.expects(size_of::() == 128 && align_of::() == 4 && align_of::() == 4); +} + +@test def writes_and_reads_its_shapes(t: &mut tester): void { + # Each is written by its fields' names, its vectors as `linear` writes them. + val box := bounds::around(vec3{ 1, 2, 3 }, vec3{ 0.5, 0.5, 0.5 }); + val text := json::to_text(&box) else (_) { + t.expects(false); + return; + }; + t.expects(text.span == "{\"min\":{\"x\":0.5,\"y\":1.5,\"z\":2.5},\"max\":{\"x\":1.5,\"y\":2.5,\"z\":3.5}}"); + t.expects(json::from_text::(text.span).value == box); + val ball := sphere{ vec3{ 0, 1, 0 }, 0.75 }; + t.expects(json::from_text::(json::to_text(&ball).value.span).value == ball); + val floor := plane::through(vec3{ 0, 2, 0 }, vec3::up); + t.expects(json::from_text::(json::to_text(&floor).value.span).value == floor); + val look := ray::toward(vec3::zero, vec3{ 0, 0, -4 }); + t.expects(json::from_text::(json::to_text(&look).value.span).value == look); +} + +@test def measures_planes(t: &mut tester): void { + val floor := plane::through(vec3{ 0, 2, 0 }, vec3{ 0, 5, 0 }); + t.expects(floor.normal == vec3::up && floor.distance == 2); + t.expects(floor.distance_to(vec3{ 3, 5, -1 }) == 3 && floor.distance_to(vec3::zero) == -2); + t.expects(floor.closest(vec3{ 3, 5, -1 }) == vec3{ 3, 2, -1 } && floor.flipped().distance_to(vec3::zero) == 2); + # Turning counterclockwise as seen from +z, it faces +z. + val wall := plane::of_points(vec3{ 0, 0, 1 }, vec3{ 1, 0, 1 }, vec3{ 0, 1, 1 }); + t.expects(wall.normal == vec3::back && wall.distance == 1); + t.expects(floor.side_of(bounds::around(vec3{ 0, 4, 0 }, vec3::one)) == side::front); + t.expects(floor.side_of(bounds::around(vec3{ 0, 2.5, 0 }, vec3::one)) == side::across); + t.expects(floor.side_of(bounds::around(vec3{ 5, -1, 5 }, vec3::one)) == side::back); + # A sphere touching it is on both sides. + t.expects(floor.side_of(sphere{ vec3::zero, 2 }) == side::across && floor.side_of(sphere{ vec3{ 0, -1, 0 }, 2 }) == side::back); +} + +@test def holds_and_meets_boxes_and_spheres(t: &mut tester): void { + val b := bounds{ vec3{ -1, 0, -1 }, vec3{ 1, 2, 1 } }; + t.expects(b.center == vec3{ 0, 1, 0 } && b.size == vec3{ 2, 2, 2 } && b.half_size == vec3::one); + t.expects(b.contains(vec3{ 1, 2, 1 }) && !b.contains(vec3{ 1, 2.5, 1 })); + t.expects(b.contains(bounds::around(b.center, vec3{ 0.5, 0.5, 0.5 })) && !b.contains(bounds::around(b.center, vec3{ 2, 0.5, 0.5 }))); + # Touching at a corner, they meet. + t.expects(b.overlaps(bounds{ vec3{ 1, 2, 1 }, vec3{ 3, 3, 3 } }) && !b.overlaps(bounds{ vec3{ 1.5, 0, 0 }, vec3{ 3, 1, 1 } })); + t.expects(b.closest(vec3{ 5, 1, -3 }) == vec3{ 1, 1, -1 } && b.closest(vec3{ 0, 1, 0 }) == vec3{ 0, 1, 0 }); + val points: vec3[3] = [vec3{ 1, 5, -2 }, vec3{ -3, 0, 4 }, vec3{ 2, 1, 0 }]; + t.expects(bounds::of(points[:]) == bounds{ vec3{ -3, 0, -2 }, vec3{ 2, 5, 4 } } && bounds::of(points[0:0]) == bounds::blank); + t.expects(bounds::blank.empty && !b.empty && bounds::blank.including(vec3::one) == bounds{ vec3::one, vec3::one }); + t.expects(b.merged(bounds::around(vec3{ 4, 0, 0 }, vec3::one)) == bounds{ vec3{ -1, -1, -1 }, vec3{ 5, 2, 1 } }); + # A quarter turn about z takes the box's reach along y to x, and along x to y. + val quarter := quat::axis_angle(vec3::back, math::pi as f32 / 2); + val turned := bounds::around(vec3::zero, vec3{ 1, 2, 3 }).transformed(mat4::compose(vec3{ 10, 0, 0 }, quarter, vec3::one)); + t.expects(near(turned.min, vec3{ 8, -1, -3 }) && near(turned.max, vec3{ 12, 1, 3 })); + t.expects(bounds::blank.transformed(mat4::identity).empty); + + val s := sphere{ vec3::zero, 2 }; + t.expects(s.contains(vec3{ 0, 2, 0 }) && !s.contains(vec3{ 1.5, 1.5, 0 })); + # Touching, they meet. + t.expects(s.overlaps(sphere{ vec3{ 3, 0, 0 }, 1 }) && !s.overlaps(sphere{ vec3{ 3, 0, 0.5 }, 0.9 })); + t.expects(s.overlaps(b) && b.overlaps(s) && !s.overlaps(bounds::around(vec3{ 3, 3, 0 }, vec3::one))); + t.expects(bounds::of(s) == bounds::around(vec3::zero, vec3{ 2, 2, 2 })); + t.expects(sphere::of(b).center == b.center && near(sphere::of(b).radius, math::sqrt(3f))); +} + +@test def casts_rays(t: &mut tester): void { + val r := ray::toward(vec3{ 0, 0, 10 }, vec3::zero); + t.expects(r.direction == vec3::forward && r.at(4) == vec3{ 0, 0, 6 }); + t.expects(r.closest(vec3{ 3, 0, 5 }) == vec3{ 0, 0, 5 } && r.closest(vec3{ 0, 0, 20 }) == r.origin); + # A wall ahead is met from in front, and one behind, and a floor it runs beside, aren't. + t.expects(hit_at(r.hit(plane::through(vec3{ 0, 0, 1 }, vec3::back))) == 9); + t.expects(hit_at(r.hit(plane::through(vec3{ 0, 0, 1 }, vec3::forward))) == 9); + t.expects(hit_at(r.hit(plane::through(vec3{ 0, 0, 11 }, vec3::back))) == -1 && hit_at(r.hit(plane::through(vec3::zero, vec3::up))) == -1); + # A sphere ahead is met at its surface, one begun within at 0, and one beside or behind not at all. + t.expects(hit_at(r.hit(sphere{ vec3::zero, 2 })) == 8 && hit_at(ray{ vec3::zero, vec3::up }.hit(sphere{ vec3::zero, 2 })) == 0); + t.expects(hit_at(r.hit(sphere{ vec3{ 3, 0, 0 }, 2 })) == -1 && hit_at(r.hit(sphere{ vec3{ 0, 0, 12 }, 1 })) == -1); + # A box ahead is met at its face, one begun within at 0, and one beside or behind not at all. + val b := bounds::around(vec3::zero, vec3::one); + t.expects(hit_at(r.hit(b)) == 9 && hit_at(ray{ vec3::zero, vec3{ 1, 2, 3 } }.hit(b)) == 0); + t.expects(hit_at(r.hit(bounds::around(vec3{ 3, 0, 0 }, vec3::one))) == -1 && hit_at(r.hit(bounds::around(vec3{ 0, 0, 12 }, vec3::one))) == -1); + # Slanting in, it meets the box where it crosses x = -1. + t.expects(near(hit_at(ray::toward(vec3{ -5, -5, 0 }, vec3::zero).hit(b)), 4 * math::sqrt(2f))); +} + +@test def culls_by_a_cameras_frustum(t: &mut tester): void { + # Looking from z = 10 at the origin, a quarter turn wide, from 1 to 100 away. + val f := frustum::of(mat4::perspective(math::pi as f32 / 2, 1, 1, 100) * mat4::look_at(vec3{ 0, 0, 10 }, vec3::zero)); + # Its planes face in, so the place it looks at is in front of each. + for p in f.planes { + t.expects(p.distance_to(vec3::zero) > 0 && near(p.normal.length, 1)); + } + # The far plane is the difference of two rows nearly alike, so as near as an `f32` of 90 gets. + t.expects(near(f.planes[4].distance_to(vec3{ 0, 0, 9 }), 0) && math::abs(f.planes[5].distance_to(vec3{ 0, 0, -90 })) < 1e-3); + t.expects(f.contains(vec3::zero) && f.contains(vec3{ 9, 0, 0 })); + t.expects(!f.contains(vec3{ 0, 0, 9.5 }) && !f.contains(vec3{ 0, 0, -95 }) && !f.contains(vec3{ 11, 0, 0 }) && !f.contains(vec3{ 0, -11, 0 })); + # A box or sphere reaching in from beside is seen, and one wholly beside or behind isn't. + t.expects(f.overlaps(bounds::around(vec3{ 11, 0, 0 }, vec3{ 2, 1, 1 })) && !f.overlaps(bounds::around(vec3{ 14, 0, 0 }, vec3{ 2, 1, 1 }))); + t.expects(f.overlaps(bounds::around(vec3{ 0, 0, 9.5 }, vec3::one)) && !f.overlaps(bounds::around(vec3{ 0, 0, 12 }, vec3::one))); + t.expects(f.overlaps(sphere{ vec3{ 0, 0, 9.5 }, 1 }) && !f.overlaps(sphere{ vec3{ 0, 0, 11 }, 1 })); + t.expects(f.overlaps(sphere{ vec3{ 0, 11, 0 }, 1.5 }) && !f.overlaps(sphere{ vec3{ 0, 13, 0 }, 1.5 })); + # Made of its own planes, it's the same. + val again := frustum::of_planes(f.planes); + for i in 0..6u { + t.expects(again.planes[i] == f.planes[i]); + } + # A projection alone gives the frustum in the camera's space, an orthographic one a box. + val o := frustum::of(mat4::orthographic(-10, 10, -10, 10, 0, 50)); + t.expects(o.contains(vec3{ 9.5, -9.5, -49 }) && !o.contains(vec3{ 10.5, 0, -1 }) && !o.contains(vec3{ 0, 0, 1 }) && !o.contains(vec3{ 0, 0, -51 })); +} + +# The bits of each number, folded together, as FNV-1a folds bytes, wrapping +# as it does. +def fold(hash: u64, x: f32): u64 { + var held := x; + val bits := ((&mut held) as *mut u32)[0] as u64; + return math::wrapping_mul(hash ^ bits, 0x100000001B3); +} + +def fold(hash: u64, v: vec3): u64 { + return fold(fold(fold(hash, v.x), v.y), v.z); +} + +def fold(hash: u64, yes: bool): u64 { + return math::wrapping_mul(hash ^ (yes ? 1u : 2u), 0x100000001B3); +} + +@test def gives_the_same_bits_as_lanes_or_not(t: &mut tester): void { + var h: u64 = 0xCBF29CE484222325; + val f := frustum::of(mat4::perspective(1.1, 1.5, 0.5, 60) * mat4::look_at(vec3{ 3, 4, 12 }, vec3{ 0, 1, 0 })); + val turn := quat::axis_angle(vec3{ 0.2, 1, -0.4 }, 0.37); + var p := vec3{ 0.3, -1.7, 2.9 }; + for i in 0..64u { + p = turn * (p * 1.07 + vec3{ 0.11, -0.05, 0.2 }); + val b := bounds::around(p, (turn * vec3{ 0.5, 1.25, 0.75 }).abs()); + val s := sphere{ p * 0.5, 1.5 }; + val r := ray::toward(vec3{ 20, -3, 7 }, p); + val wall := plane::of_points(p, p + vec3::right, p + turn * vec3::up); + val moved := b.transformed(mat4::compose(p, turn, vec3{ 1, 2, 0.5 })); + h = fold(fold(fold(h, moved.min), moved.max), b.closest(s.center)); + h = fold(fold(fold(h, hit_at(r.hit(b))), hit_at(r.hit(s))), hit_at(r.hit(wall))); + h = fold(fold(fold(h, r.closest(s.center)), wall.distance_to(s.center)), wall.closest(vec3::zero)); + h = fold(fold(fold(h, f.contains(p)), f.overlaps(b)), f.overlaps(s)); + h = fold(fold(fold(h, b.overlaps(s)), s.overlaps(moved)), b.overlaps(moved)); + h = fold(fold(h, wall.side_of(b) == side::across), wall.side_of(s) == side::front); + } + val corners: vec3[3] = [p, p * 2, -p]; + h = fold(fold(h, sphere::of(bounds::of(corners[:])).radius), f.planes[3].normal); + t.expects(h == expected_bits); +} + +# What `gives_the_same_bits_as_lanes_or_not` folds, as the machine works it a +# number at a time. +const expected_bits: u64 = 16338969092856802616; diff --git a/tests/joints2d.sakura b/tests/joints2d.sakura new file mode 100644 index 0000000..1039d5d --- /dev/null +++ b/tests/joints2d.sakura @@ -0,0 +1,101 @@ +#! Contains the tests of `physics2d`'s joints that slide and drive: a block on +#! a prismatic joint slid by its motor to its limit, a cart riding wheels on +#! their springs, driven by their motors, a body driven by a motor joint to a +#! place and an angle, and one dragged by a mouse joint. + +import std::testing; +import std::math; +import malunal::linear; +import malunal::physics2d; + +def within(a: f32, b: f32, by: f32): bool { + return math::abs(a - b) <= by; +} + +def seconds(s: &mut space, count: f32): void { + val n := (count * 60) as u32; + for i in 0..n { + s.step(1f / 60f); + } +} + +@test def slides_along_prismatic_joints(t: &mut tester): void { + var s := space::new(); + val ground := s.add(body{ kind = body_kind::static }); + val block := s.add(body{ at = pose::of(vec2{ 0, 2 }) }); + _ = s.attach(block, collider{ shape = shape::box(vec2{ 0.5, 0.25 }) }); + val rail := s.slide(ground, block, vec2{ 0, 2 }, vec2{ 1, 0 }); + var made := s.joint_of(rail); + made.motor = true; + made.motor_speed = 2; + made.max_motor_force = 100; + made.limit = true; + made.lower = -1; + made.upper = 3; + s.change(rail, made); + seconds(&mut s, 3); + # Held to its rail against gravity, unturned, it stops at its limit. + val at := s.pose_of(block); + t.expects(within(at.at.x, 3, 0.02) && within(at.at.y, 2, 0.01) && within(at.turn.angle, 0, 0.01)); + t.expects(within(s.translation_of(rail), 3, 0.02)); +} + +@test def rides_wheels(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, -1 }) }); + _ = s.attach(ground, collider{ shape = shape::box(vec2{ 100, 1 }), friction = 0.9 }); + val cart := s.add(body{ at = pose::of(vec2{ 0, 1 }) }); + _ = s.attach(cart, collider{ shape = shape::box(vec2{ 1, 0.2 }) }); + var axles: joint_id[2] = [joint_id{}, joint_id{}]; + for i in 0..2u { + val x := i == 0 ? -0.8f : 0.8f; + val wheel := s.add(body{ at = pose::of(vec2{ x, 0.5 }) }); + _ = s.attach(wheel, collider{ shape = shape::circle(0.3), friction = 0.9 }); + axles[i] = s.wheel(cart, wheel, vec2{ x, 0.5 }, vec2{ 0, 1 }); + } + seconds(&mut s, 1); + # Resting on its springs, the cart's held above its wheels, level. + val resting := s.pose_of(cart); + t.expects(resting.at.y > 0.6 && resting.at.y < 1.1 && within(resting.turn.angle, 0, 0.02) && within(resting.at.x, 0, 0.05)); + # Their motors turning them clockwise, it drives right. + for i in 0..2u { + var made := s.joint_of(axles[i]); + made.motor = true; + made.motor_speed = -10; + made.max_motor_force = 50; + s.change(axles[i], made); + } + seconds(&mut s, 2); + t.expects(s.pose_of(cart).at.x > 3 && within(s.pose_of(cart).turn.angle, 0, 0.1)); +} + +@test def drives_bodies_by_motor_joints(t: &mut tester): void { + var s := space::new(vec2::zero); + val base := s.add(body{ kind = body_kind::static }); + val puck := s.add(body{ at = pose::of(vec2{ 1, 0 }) }); + _ = s.attach(puck, collider{ shape = shape::box(vec2{ 0.3, 0.3 }) }); + val driven := s.drive(base, puck, 50, 20); + # Where it's driven, it stays; driven elsewhere, it goes, and turns. + seconds(&mut s, 0.5); + t.expects(within(s.pose_of(puck).at.x, 1, 0.01) && within(s.pose_of(puck).at.y, 0, 0.01)); + s.drive_to(driven, vec2{ 3, 2 }, 1); + seconds(&mut s, 4); + val at := s.pose_of(puck); + t.expects(within(at.at.x, 3, 0.05) && within(at.at.y, 2, 0.05) && within(at.turn.angle, 1, 0.05)); +} + +@test def drags_bodies_by_mouse_joints(t: &mut tester): void { + var s := space::new(); + val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, -1 }) }); + _ = s.attach(ground, collider{ shape = shape::box(vec2{ 20, 1 }) }); + val crate := s.add(body{ at = pose::of(vec2{ 0, 0.5 }) }); + _ = s.attach(crate, collider{ shape = shape::box(vec2{ 0.5, 0.5 }) }); + # Grabbed by its top and pulled up and over, it hangs below the target. + val hand := s.grab(ground, crate, vec2{ 0, 1 }, 1000); + s.drive_to(hand, vec2{ 4, 3 }); + seconds(&mut s, 3); + val at := s.pose_of(crate); + t.expects(within(at.apply(vec2{ 0, 0.5 }).x, 4, 0.1) && within(at.apply(vec2{ 0, 0.5 }).y, 3, 0.1)); + t.expects(at.at.y < 3); +} diff --git a/tests/linear.sakura b/tests/linear.sakura new file mode 100644 index 0000000..8dcf8b4 --- /dev/null +++ b/tests/linear.sakura @@ -0,0 +1,235 @@ +#! Contains the tests of `linear`: vectors of two, three, and four; rotations; +#! matrices of three and four; projections; values read as lanes where they lie +#! unaligned; and the same bits whether numbers are worked as lanes or one at a +#! time, which `malunal.linear.tests` and `malunal.linear.lanes.tests` each +#! check. + +import std::testing; +import std::json; +import std::math; +import std::serial; +import malunal::linear; + +# Whether two numbers are within a millionth or so of one another. +def near(a: f32, b: f32): bool { + return math::abs(a - b) < 1e-5; +} + +def near(a: vec3, b: vec3): bool { + return near(a.x, b.x) && near(a.y, b.y) && near(a.z, b.z); +} + +def near(a: &mat4, b: &mat4): bool { + for i in 0..16u { + return false if !near(a.m[i], b.m[i]); + } + return true; +} + +def near(a: &mat3, b: &mat3): bool { + return near(a.x_axis, b.x_axis) && near(a.y_axis, b.y_axis) && near(a.z_axis, b.z_axis); +} + +@test def lays_out_its_numbers_as_lanes(t: &mut tester): void { + t.expects(size_of::() == 8 && size_of::() == 16 && size_of::() == 16 && size_of::() == 16); + t.expects(size_of::() == 48 && size_of::() == 64); + # Each is of `f32`s, so a field of one is wherever the struct holding it puts it. + t.expects(align_of::() == 4 && align_of::() == 4); + val v := vec3{ 1, 2, 3 }; + t.expects(v.x == 1 && v.y == 2 && v.z == 3 && vec3{ y = 5 } == vec3{ 0, 5, 0 }); +} + +@test def adds_scales_and_measures_vectors(t: &mut tester): void { + val a := vec3{ 1, 2, 3 }; + val b := vec3{ 4, -5, 6 }; + t.expects(a + b == vec3{ 5, -3, 9 } && a - b == vec3{ -3, 7, -3 } && -a == vec3{ -1, -2, -3 }); + t.expects(a * 2 == vec3{ 2, 4, 6 } && a * b == vec3{ 4, -10, 18 } && b / 2 == vec3{ 2, -2.5, 3 }); + t.expects(b / a == vec3{ 4, -2.5, 2 }); + t.expects(a.dot(b) == 12 && a.length_squared == 14 && near(a.length, math::sqrt(14f))); + t.expects(near(a.normalized().length, 1) && vec3::zero.normalized() == vec3::zero); + t.expects(near(vec3{ 0, 3, 4 }.distance(vec3::zero), 5)); + t.expects(a.lerp(b, 0.5) == vec3{ 2.5, -1.5, 4.5 }); + t.expects(a.min(b) == vec3{ 1, -5, 3 } && a.max(b) == vec3{ 4, 2, 6 } && b.abs() == vec3{ 4, 5, 6 }); + t.expects(vec3::right.cross(vec3::up) == vec3::back && vec3::up.cross(vec3::right) == vec3::forward); + + val c := vec2{ 3, 4 }; + t.expects(c + vec2::one == vec2{ 4, 5 } && c * 2 == vec2{ 6, 8 } && c.length == 5 && c.dot(vec2{ 1, 1 }) == 7); + t.expects(vec2{ 1, 0 }.cross(vec2{ 0, 1 }) == 1 && vec2{ 1, 0 }.perpendicular() == vec2{ 0, 1 }); + t.expects(near(c.normalized().length, 1) && c.lerp(vec2::zero, 0.5) == vec2{ 1.5, 2 }); + + val d := vec4{ 1, 2, 3, 4 }; + t.expects(d + vec4::one == vec4{ 2, 3, 4, 5 } && d * 0.5 == vec4{ 0.5, 1, 1.5, 2 } && d.dot(d) == 30); + t.expects(d.xyz == a && -d == vec4{ -1, -2, -3, -4 } && near(d.normalized().length, 1)); + t.expects(d.min(vec4{ 2, 2, 2, 2 }) == vec4{ 1, 2, 2, 2 } && (d - vec4{ 5, 5, 5, 5 }).abs() == vec4{ 4, 3, 2, 1 }); +} + +@test def turns_and_moves_vectors(t: &mut tester): void { + val quarter: f32 = math::pi as f32 / 2; + # A quarter turn about y takes x to -z, and about z takes x to y. + t.expects(near(quat::axis_angle(vec3::up, quarter) * vec3::right, vec3{ 0, 0, -1 })); + t.expects(near(quat::axis_angle(vec3::back, quarter) * vec3::right, vec3::up)); + # Turning by a rotation and then back changes nothing. + val q := quat::euler(0.3, -1.1, 0.7); + t.expects(near(q.length, 1) && near(q.inverse() * (q * vec3{ 1, 2, 3 }), vec3{ 1, 2, 3 })); + # Turning by one rotation after another is turning by their product. + val r := quat::axis_angle(vec3{ 1, 1, 0 }, 0.4); + t.expects(near((q * r) * vec3{ 1, 2, 3 }, q * (r * vec3{ 1, 2, 3 }))); + # A matrix composed of a transform does what the transform does. + val m := mat4::compose(vec3{ 5, 0, -2 }, q, vec3{ 2, 2, 2 }); + t.expects(near(m.transform_point(vec3{ 1, 0, 0 }), vec3{ 5, 0, -2 } + q * vec3{ 2, 0, 0 })); + t.expects(near(m.transform_vector(vec3{ 1, 0, 0 }), q * vec3{ 2, 0, 0 })); + t.expects(near(&(m * m.inverse()), &mat4::identity)); + val p := m * vec4{ 1, 0, 0, 1 }; + t.expects(near(p.xyz, m.transform_point(vec3{ 1, 0, 0 })) && near(p.w, 1)); + # Halfway between no turn and a third of one is a sixth. + val half := quat::identity.slerp(quat::axis_angle(vec3::up, 4 * quarter / 3), 0.5); + t.expects(near(half * vec3::right, vec3{ 0.5, 0, -math::sqrt(3f) / 2 })); + # Looking at a place turns -z toward it. + t.expects(near(quat::looking(vec3{ 1, 0, 0 }) * vec3::forward, vec3::right)); + # The shortest turn between two directions takes one to the other, the + # same one not at all, and opposite ones by half a turn. + t.expects(near(quat::between(vec3::up, vec3{ 0.6, 0.8, 0 }) * vec3::up, vec3{ 0.6, 0.8, 0 })); + t.expects(near(quat::between(vec3::right, vec3::right).w, 1)); + t.expects(near(quat::between(vec3::up, vec3{ 0, -1, 0 }) * vec3::up, vec3{ 0, -1, 0 })); + # Turning y to a way across it leaves what's across both where it was. + val tilted := quat::between(vec3::up, vec3{ 0, 0.6, 0.8 }); + t.expects(near(tilted * vec3::right, vec3::right) && near(tilted * vec3::back, vec3{ 0, -0.8, 0.6 })); +} + +@test def projects_into_clip_space(t: &mut tester): void { + # The near plane is depth 0, the far one 1, and y points up. + val p := mat4::perspective(math::pi as f32 / 2, 2, 1, 100); + val near_point := p * vec4{ 0, 1, -1, 1 }; + t.expects(near(near_point.z / near_point.w, 0) && near(near_point.y / near_point.w, 1)); + val far_point := p * vec4{ 0, 0, -100, 1 }; + t.expects(near(far_point.z / far_point.w, 1)); + val o := mat4::orthographic(0, 200, 100, 0, -1, 1); + val corner := o * vec4{ 200, 100, 0, 1 }; + t.expects(near(corner.x, 1) && near(corner.y, -1) && near(corner.z, 0.5)); + # A camera looking at the origin from +z sees it straight ahead. + val view := mat4::look_at(vec3{ 0, 0, 10 }, vec3::zero); + t.expects(near(view.transform_point(vec3::zero), vec3{ 0, 0, -10 })); + # A projection is undone, and a scale of zero can't be. + val clip := p * view; + t.expects(near(&(clip * clip.inverse()), &mat4::identity) && near(&(clip.inverse() * clip), &mat4::identity)); + t.expects(mat4::scaling(vec3::zero).inverse() == mat4{}); +} + +@test def works_matrices_of_three(t: &mut tester): void { + val q := quat::euler(0.3, -1.1, 0.7); + val r := mat3::rotation(q); + # A rotation's matrix turns as the rotation does, and its transpose back. + t.expects(near(r * vec3{ 1, 2, 3 }, q * vec3{ 1, 2, 3 }) && near(&(r * r.transposed()), &mat3::identity)); + t.expects(near(r.determinant, 1) && near(&r.inverse(), &r.transposed())); + # The rotation of a rotation's matrix is the rotation. + val back := quat::of_basis(r.x_axis, r.y_axis, r.z_axis); + t.expects(near(back * vec3{ 1, 2, 3 }, q * vec3{ 1, 2, 3 })); + val s := mat3::scaling(vec3{ 2, 4, 8 }); + t.expects(s.determinant == 64 && near(&(s * s.inverse()), &mat3::identity) && mat3::scaling(vec3::zero).inverse() == mat3{}); + t.expects(near(&(r * s), &mat4::compose(vec3::zero, q, vec3{ 2, 4, 8 }).linear_part())); + t.expects(s + s == s * 2 && (s - s) == mat3{}); +} + +# A value lying where a struct puts it, four bytes past a 16-byte boundary. +struct placed { + var tag: u32; + var at: vec3; + var turn: quat; + var by: mat4; +} + +@test def reads_values_where_they_lie(t: &mut tester): void { + var p := placed{ tag = 7, at = vec3{ 1, 2, 3 }, turn = quat::axis_angle(vec3::back, math::pi as f32 / 2), by = mat4::translation(vec3{ 1, 1, 1 }) }; + p.at = p.at * 2 + vec3::one; + t.expects(p.tag == 7 && p.at == vec3{ 3, 5, 7 }); + t.expects(near(p.turn * vec3::right, vec3::up) && near(p.by.transform_point(p.at), vec3{ 4, 6, 8 })); + t.expects(near(&(p.by * p.by), &mat4::translation(vec3{ 2, 2, 2 }))); + # Its lanes, and a vector of lanes. + val l := p.at.lanes(); + t.expects(l[0] == 3 && l[1] == 5 && l[2] == 7 && vec3::of_lanes(l) == p.at); + t.expects(vec4::of_lanes(f32x4::of([1.0, 2.0, 3.0, 4.0])) == vec4{ 1, 2, 3, 4 }); +} + +@serial +struct posed { + @serial var at: vec3; + @serial var turn: quat; + @serial var by: mat3; + @serial var size: vec2; + @serial var tint: vec4; +} + +@test def writes_and_reads_its_types(t: &mut tester): void { + # Each is written by its numbers' names, as the shortest text reading back as + # each `f32`, but a `mat4`, as its 16 numbers; `vec3`'s fourth isn't written. + val written := posed{ + at = vec3{ 1, 0.1, -2.5 }, turn = quat::axis_angle(vec3::up, 1), by = mat3::scaling(vec3{ 2, 3, 4 }), + size = vec2{ 0.5, 8 }, tint = vec4{ 1, 0.25, 0, 1 }, + }; + val text := json::to_text(&written) else (_) { + t.expects(false); + return; + }; + t.expects(text.span.find("\"at\":{\"x\":1,\"y\":0.1,\"z\":-2.5}") is some(_)); + t.expects(text.span.find("\"size\":{\"x\":0.5,\"y\":8}") is some(_) && text.span.find("_w") is none); + val back := json::from_text::(text.span) else (_) { + t.expects(false); + return; + }; + t.expects(back.at == written.at && back.turn == written.turn && back.by == written.by); + t.expects(back.size == written.size && back.tint == written.tint); + + val moved := mat4::compose(vec3{ 1, 2, 3 }, written.turn, vec3{ 2, 2, 2 }); + val matrix := json::to_text(&moved) else (_) { + t.expects(false); + return; + }; + t.expects(matrix.span.starts_with("[") && json::from_text::(matrix.span).value == moved); + t.expects(json::from_text::("[1, 0, 0, 1]").error.kind == json::error_kind::wrong_kind); + + # What's left out reads as each number's default, where asked: a rotation's + # `w` of 1, and 0 for the rest. + val lenient := serial::options{ defaults = true }; + t.expects(json::from_text::("{}", lenient).value == quat::identity); + t.expects(json::from_text::("{\"y\": 2}", lenient).value == vec3{ 0, 2, 0 }); +} + +# The bits of each number, folded together, as FNV-1a folds bytes, wrapping +# as it does. +def fold(hash: u64, x: f32): u64 { + var held := x; + val bits := ((&mut held) as *mut u32)[0] as u64; + return math::wrapping_mul(hash ^ bits, 0x100000001B3); +} + +def fold(hash: u64, v: vec3): u64 { + return fold(fold(fold(hash, v.x), v.y), v.z); +} + +def fold(hash: u64, q: quat): u64 { + return fold(fold(fold(fold(hash, q.x), q.y), q.z), q.w); +} + +@test def gives_the_same_bits_as_lanes_or_not(t: &mut tester): void { + var h: u64 = 0xCBF29CE484222325; + var v := vec3{ 0.1, -2.3, 4.5 }; + var q := quat::euler(0.2, 0.9, -0.4); + var m := mat4::compose(vec3{ 1, 2, 3 }, q, vec3{ 1.5, 0.5, 2 }); + val turn := quat::axis_angle(vec3{ 0.3, 1, -0.2 }, 0.05); + for i in 0..64u { + v = (v + vec3{ 0.25, 0.5, -0.125 }) * 0.9; + v = q * v; + v = m.transform_point(v) - m.transform_vector(v).normalized(); + q = (q * turn).normalized(); + m = m * mat4::rotation(turn); + h = fold(fold(fold(h, v), q), v.dot(vec3{ 1, 2, 3 })); + h = fold(h, (m * vec4{ v.x, v.y, v.z, 1 }).w); + h = fold(h, (mat3::rotation(q) * v).lerp(v.min(vec3::one).abs(), 0.25)); + } + h = fold(fold(h, q.slerp(quat::identity, 0.3)), m.inverse().m[7]); + t.expects(h == expected_bits); +} + +# What `gives_the_same_bits_as_lanes_or_not` folds, as the machine works it a +# number at a time. +const expected_bits: u64 = 2409136494821621507; diff --git a/tests/main.sakura b/tests/main.sakura new file mode 100644 index 0000000..f2dc1be --- /dev/null +++ b/tests/main.sakura @@ -0,0 +1,11 @@ +#! Contains the `main` that runs the tests of `linear`, `geometry`, +#! `photometry`, and `physics2d`, each in a copy of the program of its own. +#! `blossom test` runs them, and `--test TEXT` those whose name holds the +#! text. + +import system; +import std::testing; + +def main(args: span): void { + exit(tester::run(args)); +} diff --git a/tests/motion2d.sakura b/tests/motion2d.sakura new file mode 100644 index 0000000..02b664b --- /dev/null +++ b/tests/motion2d.sakura @@ -0,0 +1,251 @@ +#! Contains the tests of how `physics2d` keeps what moves fast from passing +#! through what's thin, and what a space is asked of the shapes in it: gaps +#! between shapes, shapes cast along motions, times of impact, bodies swept +#! through a step, bullets, chains of segments, one-way platforms, and which +#! colliders a shape overlaps or a cast meets. + +import std::testing; +import std::containers; +import std::math; +import malunal::linear; +import malunal::physics2d; + +def near(a: f32, b: f32, within: f32): bool { + return math::abs(a - b) <= within; +} + +def run(s: &mut space, seconds: f32): void { + val n := (seconds * 60) as u32; + for i in 0..n { + s.step(1f / 60f); + } +} + +@test def finds_gaps_between_shapes(t: &mut tester): void { + val crate := shape::box(vec2{ 0.5, 0.5 }); + # Two boxes side by side, a meter between their faces. + val apart := gap_between(&crate, pose::identity, &crate, pose::of(vec2{ 2, 0.25 })); + t.expects(near(apart.distance, 1, 1e-5) && near(apart.normal.x, 1, 1e-5) && near(apart.on_a.x, 0.5, 1e-5) && near(apart.on_b.x, 1.5, 1e-5)); + # A ball off a box's corner: along the diagonal. + val ball := shape::circle(0.25); + val corner := gap_between(&crate, pose::identity, &ball, pose::of(vec2{ 1.5, 1.5 })); + t.expects(near(corner.distance, math::sqrt(2f) - 0.25, 1e-4) && near(corner.normal.x, corner.normal.y, 1e-4)); + # A turned box against a capsule, by their radii. + val pill := shape::capsule(vec2{ 0, -1 }, vec2{ 0, 1 }, 0.3); + val turned := gap_between(&pill, pose::of(vec2{ -2, 0 }), &crate, pose::of(vec2::zero, math::pi as f32 / 4)); + t.expects(near(turned.distance, 2 - 0.3 - math::sqrt(0.5f), 1e-4) && near(turned.normal.x, 1, 1e-4)); + # Overlapping: no distance. + val within := gap_between(&crate, pose::identity, &ball, pose::of(vec2{ 0.3, 0 })); + t.expects(within.distance == 0); +} + +@test def casts_shapes_along_motions(t: &mut tester): void { + val wall := shape::box(vec2{ 0.1, 2 }); + val ball := shape::circle(0.5); + # A ball cast 10 meters toward a wall 5 meters off meets it halfway, by its + # face facing back. + val hit := shape_cast(&wall, pose::of(vec2{ 5, 0 }), &ball, pose::identity, vec2{ 10, 0 }) else { t.expects(false); return; }; + t.expects(near(hit.fraction, (4.9 - 0.5) / 10, 1e-3) && near(hit.normal.x, -1, 1e-4) && near(hit.point.x, 4.9, 1e-3)); + # Cast short of it, or away, it meets nothing. + t.expects(!(shape_cast(&wall, pose::of(vec2{ 5, 0 }), &ball, pose::identity, vec2{ 4, 0 }) is some(_))); + t.expects(!(shape_cast(&wall, pose::of(vec2{ 5, 0 }), &ball, pose::identity, vec2{ -10, 0 }) is some(_))); + # Begun within it, it meets it at once. + val inside := shape_cast(&wall, pose::of(vec2{ 5, 0 }), &ball, pose::of(vec2{ 4.8, 0 }), vec2{ 1, 0 }) else { t.expects(false); return; }; + t.expects(inside.fraction == 0); + # A box cast down onto a turned box meets its corner. + val crate := shape::box(vec2{ 0.5, 0.5 }); + val down := shape_cast(&crate, pose::of(vec2::zero, math::pi as f32 / 4), &crate, pose::of(vec2{ 0, 3 }), vec2{ 0, -3 }) else { t.expects(false); return; }; + t.expects(near(3 - down.fraction * 3, math::sqrt(0.5f) + 0.5, 3e-3) && near(down.normal.y, 1, 1e-3)); +} + +@test def finds_times_of_impact(t: &mut tester): void { + val wall := shape::box(vec2{ 0.05, 2 }); + val stick := shape::box(vec2{ 1, 0.05 }); + # A stick turning nearly a half turn about its middle, under a shelf off to + # its right, meets it as its end rises to it. + val shelf := shape::box(vec2{ 0.9, 0.02 }); + val turning := sweep{ c1 = vec2::zero, c2 = vec2::zero, q1 = rot::identity, q2 = rot::of(math::pi as f32 * 0.99) }; + val at := time_of_impact(&shelf, &sweep::still(pose::of(vec2{ 1.1, 0.85 })), &stick, &turning, 0.005, 0.001); + val angle := math::pi as f32 * 0.99 * at; + t.expects(at > 0.2 && at < 0.45 && near(math::sin(angle + 0.05), 0.83, 0.03)); + # One moving away never meets it. + val leaving := sweep{ c1 = vec2{ -1.5, 0 }, c2 = vec2{ -3, 0 } }; + t.expects(time_of_impact(&wall, &sweep::still(pose::identity), &stick, &leaving, 0.005, 0.001) == 1); +} + +# A thin wall, and a ball thrown at it faster than it's thick each step. +def thrown(continuous: bool, bullet: bool): f32 { + var s := space::new(vec2::zero); + s.continuous = continuous; + val wall := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 5.5, 0 }) }); + _ = s.attach(wall, collider{ shape = shape::box(vec2{ 0.02, 3 }) }); + val ball := s.add(body{ velocity = vec2{ 300, 0 }, bullet = bullet }); + _ = s.attach(ball, collider{ shape = shape::circle(0.1) }); + run(&mut s, 0.5); + return s.pose_of(ball).at.x; +} + +@test def keeps_fast_bodies_from_passing_through(t: &mut tester): void { + # Swept, it stops at the wall; not swept, it passes it. + t.expects(thrown(true, false) < 5.45); + t.expects(thrown(false, false) > 10); + # Dropped flat from high onto a thin floor, a crate lands on it; dropped on + # its corner, it's thrown about, but never through it. + t.expects(near(dropped(0), 0.25, 0.01)); + t.expects(dropped(0.3) > 0); +} + +# A crate dropped onto a floor as thin as a line at 200 meters a second, turned +# so, and the lowest its middle came in two seconds, or where it ended flat. +def dropped(angle: f32): f32 { + var s := space::new(); + val floor := s.add(body{ kind = body_kind::static }); + _ = s.attach(floor, collider{ shape = shape::segment(vec2{ -100, 0 }, vec2{ 100, 0 }) }); + val crate := s.add(body{ at = pose::of(vec2{ 0, 2 }, angle), velocity = vec2{ 0, -200 } }); + _ = s.attach(crate, collider{ shape = shape::box(vec2{ 0.25, 0.25 }) }); + var lowest: f32 = 2; + for i in 0..120u { + s.step(1f / 60f); + lowest = math::min(lowest, s.pose_of(crate).at.y); + } + return angle == 0 ? s.pose_of(crate).at.y : lowest; +} + +@test def sweeps_bullets_against_moving_bodies(t: &mut tester): void { + var s := space::new(vec2::zero); + val plank := s.add(body{ at = pose::of(vec2{ 5, 0 }) }); + _ = s.attach(plank, collider{ shape = shape::box(vec2{ 0.02, 1 }) }); + # Not a bullet, a shot passes through a crate; a bullet strikes it, pushing + # it on. + val shot := s.add(body{ velocity = vec2{ 400, 0 }, bullet = true }); + _ = s.attach(shot, collider{ shape = shape::circle(0.05), density = 10 }); + run(&mut s, 0.25); + t.expects(s.pose_of(shot).at.x < s.pose_of(plank).at.x && s.velocity_of(plank).x > 1); + var t2 := space::new(vec2::zero); + val other := t2.add(body{ at = pose::of(vec2{ 5, 0 }) }); + _ = t2.attach(other, collider{ shape = shape::box(vec2{ 0.02, 1 }) }); + val passing := t2.add(body{ velocity = vec2{ 400, 0 } }); + _ = t2.attach(passing, collider{ shape = shape::circle(0.05), density = 10 }); + run(&mut t2, 0.25); + t.expects(t2.pose_of(passing).at.x > 20); +} + +# Ground of segments a meter wide, running right to left so they face up. +def chained_ground(s: &mut space, count: u32): void { + var places := vector::::new(); + var i := count as i64; + while i >= 0 { + places.append(vec2{ i as f32 - 2, 0 }); + i--; + } + val ground := s.add(body{ kind = body_kind::static }); + _ = s.attach_chain(ground, places.span, false, collider{ friction = 0 }); +} + +@test def slides_along_chains(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + chained_ground(&mut s, 40); + val crate := s.add(body{ at = pose::of(vec2{ 0, 0.25 }), velocity = vec2{ 5, 0 } }); + _ = s.attach(crate, collider{ shape = shape::box(vec2{ 0.25, 0.25 }), friction = 0 }); + var lowest: f32 = 1; + var slowest: f32 = 5; + for i in 0..240u { + s.step(1f / 60f); + lowest = math::min(lowest, s.pose_of(crate).at.y); + slowest = math::min(slowest, s.velocity_of(crate).x); + } + # Across the joints it slides as along one floor: never caught, never sunk. + t.expects(slowest > 4.9 && lowest > 0.24 && near(s.pose_of(crate).turn.angle, 0, 1e-3)); + # From below, a ball rises through the chain, met only from above. + var up := space::new(vec2{ 0, -1 }); + chained_ground(&mut up, 4); + val ball := up.add(body{ at = pose::of(vec2{ 0, -1 }), velocity = vec2{ 0, 4 } }); + _ = up.attach(ball, collider{ shape = shape::circle(0.2) }); + run(&mut up, 1); + t.expects(up.pose_of(ball).at.y > 0.5); + # A ray up through it passes; one down meets it. + t.expects(!(up.ray_cast(vec2{ 0.5, -2 }, vec2{ 0, 1 }, 4) is some(_))); + t.expects(up.ray_cast(vec2{ 0.5, 2 }, vec2{ 0, -1 }, 4) is some(_)); +} + +@test def jumps_through_one_way_platforms(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + val ledge := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, 2 }) }); + _ = s.attach(ledge, collider{ shape = shape::box(vec2{ 2, 0.1 }), one_way = true }); + # Thrown up from below it, a ball passes through, then lands on it. + val ball := s.add(body{ velocity = vec2{ 0, 9 } }); + _ = s.attach(ball, collider{ shape = shape::circle(0.25) }); + var above := false; + for i in 0..180u { + s.step(1f / 60f); + if s.pose_of(ball).at.y > 2.4 { + above = true; + } + } + t.expects(above && near(s.pose_of(ball).at.y, 2.35, 0.02) && s.velocity_of(ball).length < 0.05); +} + +@test def asks_what_shapes_overlap_and_meet(t: &mut tester): void { + var s := space::new(); + val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, -1 }) }); + _ = s.attach(ground, collider{ shape = shape::box(vec2{ 10, 1 }) }); + var cells := grid::new(4, 4); + cells.set(1, 0, true); + val walls := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 6, 0 }) }); + _ = s.attach_grid(walls, move(cells), collider{}); + val crate := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ -3, 0.5 }) }); + val held := s.attach(crate, collider{ shape = shape::box(vec2{ 0.5, 0.5 }), layers = 2 }); + # A ball over the crate's corner overlaps it and the ground. + var found: u32 = 0; + var crate_found := false; + s.overlap(&shape::circle(0.3), pose::of(vec2{ -2.4, 0.1 }), 0xFFFFFFFF, def(c: collider_id, b: body_id): bool { + found++; + if c == held { + crate_found = true; + } + return true; + }); + t.expects(found == 2 && crate_found); + # Masked from the crate's layer, only the ground. + found = 0; + s.overlap(&shape::circle(0.3), pose::of(vec2{ -2.4, 0.1 }), 1, def(c: collider_id, b: body_id): bool { + found++; + return true; + }); + t.expects(found == 1); + # A ball cast right along the ground meets the grid's cell at x 7 to 8. + val ball := shape::circle(0.25); + val hit := s.shape_cast(&ball, pose::of(vec2{ 0, 0.5 }), vec2{ 20, 0 }) else { t.expects(false); return; }; + t.expects(near(hit.point.x, 7, 0.01) && near(hit.normal.x, -1, 1e-3) && hit.body == walls); + # Cast left, it meets the crate. + val left := s.shape_cast(&ball, pose::of(vec2{ 0, 0.5 }), vec2{ -20, 0 }) else { t.expects(false); return; }; + t.expects(left.collider == held && near(left.point.x, -2.5, 0.01)); +} + +# A tower of crates and a ball thrown into it, stepped a second on so many +# threads, and where its top crate ends. +def toppled(threads: u32): pose { + var s := space::new(); + s.threads = threads; + val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, -1 }) }); + _ = s.attach(ground, collider{ shape = shape::box(vec2{ 50, 1 }) }); + var top := body_id{}; + for i in 0..12u { + for j in 0..3u { + top = s.add(body{ at = pose::of(vec2{ j as f32 * 1.1 - 1.1, 0.5 + i as f32 }) }); + _ = s.attach(top, collider{ shape = shape::box(vec2{ 0.5, 0.5 }) }); + } + } + val ball := s.add(body{ at = pose::of(vec2{ -8, 4 }), velocity = vec2{ 20, 0 } }); + _ = s.attach(ball, collider{ shape = shape::circle(0.4), density = 5 }); + run(&mut s, 1); + return s.pose_of(top); +} + +@test def solves_the_same_on_several_threads(t: &mut tester): void { + val one := toppled(1); + val four := toppled(4); + t.expects(one == four && one.at.x != 1.1f); +} \ No newline at end of file diff --git a/tests/motion3d.sakura b/tests/motion3d.sakura new file mode 100644 index 0000000..b0fc594 --- /dev/null +++ b/tests/motion3d.sakura @@ -0,0 +1,292 @@ +#! Contains the tests of how `physics3d` keeps what moves fast from passing +#! through what's thin, what a space is asked of the shapes in it, heightfields, +#! and the joints that slide and limit: gaps between shapes, shapes cast along +#! motions, times of impact, bodies swept through a step, which colliders a +#! shape overlaps or a cast meets, a terrain's heights, rays, and what rolls on +#! it, a slider, a ball joint's cone and twist, and six-way joints. + +import std::testing; +import std::containers; +import std::math; +import malunal::linear; +import malunal::physics3d; + +def near(a: f32, b: f32, within: f32): bool { + return math::abs(a - b) <= within; +} + +def run(s: &mut space, seconds: f32): void { + val n := (seconds * 60) as u32; + for i in 0..n { + s.step(1f / 60f); + } +} + +@test def finds_gaps_between_shapes(t: &mut tester): void { + val crate := shape::box(vec3{ 0.5, 0.5, 0.5 }); + val apart := gap_between(&crate, pose::identity, &crate, pose::of(vec3{ 2, 0.25, -0.1 })); + t.expects(near(apart.distance, 1, 1e-4) && near(apart.normal.x, 1, 1e-4) && near(apart.on_a.x, 0.5, 1e-4)); + # A ball off a box's corner, along its diagonal. + val ball := shape::sphere(0.25); + val corner := gap_between(&crate, pose::identity, &ball, pose::of(vec3{ 1.5, 1.5, 1.5 })); + t.expects(near(corner.distance, math::sqrt(3f) - 0.25, 1e-3) && near(corner.normal.x, corner.normal.z, 1e-3)); + # A capsule lying across a turned box's top edge. + val pill := shape::capsule(vec3{ 0, 0, -2 }, vec3{ 0, 0, 2 }, 0.2); + val turned := quat::axis_angle(vec3::back, math::pi as f32 / 4); + val edge := gap_between(&crate, pose::of(vec3::zero, turned), &pill, pose::of(vec3{ 0, 2, 0 })); + t.expects(near(edge.distance, 2 - math::sqrt(0.5f) - 0.2, 1e-3) && near(edge.normal.y, 1, 1e-3)); + val within := gap_between(&crate, pose::identity, &ball, pose::of(vec3{ 0.3, 0, 0 })); + t.expects(within.distance == 0); +} + +@test def casts_shapes_along_motions(t: &mut tester): void { + val wall := shape::box(vec3{ 0.1, 2, 2 }); + val ball := shape::sphere(0.5); + val hit := shape_cast(&wall, pose::of(vec3{ 5, 0, 0 }), &ball, pose::identity, vec3{ 10, 0, 0 }) else { t.expects(false); return; }; + t.expects(near(hit.fraction, 0.44, 2e-3) && near(hit.normal.x, -1, 1e-3) && near(hit.point.x, 4.9, 2e-3)); + t.expects(!(shape_cast(&wall, pose::of(vec3{ 5, 0, 0 }), &ball, pose::identity, vec3{ 0, 10, 0 }) is some(_))); + # A box dropped onto a box turned on its corner meets the corner. + val crate := shape::box(vec3{ 0.5, 0.5, 0.5 }); + val tipped := quat::axis_angle(vec3::back, math::pi as f32 / 4) * quat::axis_angle(vec3::right, math::atan(math::sqrt(0.5f))); + val down := shape_cast(&crate, pose::of(vec3::zero, tipped), &crate, pose::of(vec3{ 0, 4, 0 }), vec3{ 0, -4, 0 }) else { t.expects(false); return; }; + t.expects(down.fraction > 0.5 && near(down.normal.y, 1, 0.02)); +} + +# A thin wall, and a ball thrown at it faster than it's thick each step. +def thrown(continuous: bool): f32 { + var s := space::new(vec3::zero); + s.continuous = continuous; + val wall := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ 5.5, 0, 0 }) }); + _ = s.attach(wall, collider{ shape = shape::box(vec3{ 0.02, 3, 3 }) }); + val ball := s.add(body{ velocity = vec3{ 300, 0, 0 } }); + _ = s.attach(ball, collider{ shape = shape::sphere(0.1) }); + run(&mut s, 0.5); + return s.pose_of(ball).at.x; +} + +# A square floor of triangles, two to a meter, its top at y 0. +def floor_mesh(): triangle_mesh { + var points := vector::::new(); + var indices := vector::::new(); + val side: u32 = 20; + for z in 0..side + 1 { + for x in 0..side + 1 { + points.append(vec3{ x as f32 - 10, 0, z as f32 - 10 }); + } + } + for z in 0..side { + for x in 0..side { + val i := (z * (side + 1) + x) as u32; + indices.append(i); + indices.append(i + side + 1); + indices.append(i + 1); + indices.append(i + 1); + indices.append(i + side + 1); + indices.append(i + side + 2); + } + } + return triangle_mesh::new(points.span, indices.span); +} + +@test def keeps_fast_bodies_from_passing_through(t: &mut tester): void { + t.expects(thrown(true) < 5.45); + t.expects(thrown(false) > 10); + # Dropped onto a mesh's floor fast enough to pass it in a step, a crate + # lands on it. + var s := space::new(); + val level := s.add(body{ kind = body_kind::static }); + _ = s.attach_mesh(level, floor_mesh(), collider{}); + val crate := s.add(body{ at = pose::of(vec3{ 0.3, 3, 0.2 }), velocity = vec3{ 0, -150, 0 } }); + _ = s.attach(crate, collider{ shape = shape::box(vec3{ 0.25, 0.25, 0.25 }) }); + var lowest: f32 = 3; + for i in 0..120u { + s.step(1f / 60f); + lowest = math::min(lowest, s.pose_of(crate).at.y); + } + t.expects(lowest > 0.2 && near(s.pose_of(crate).at.y, 0.25, 0.02)); +} + +@test def asks_what_shapes_overlap_and_meet(t: &mut tester): void { + var s := space::new(); + val level := s.add(body{ kind = body_kind::static }); + _ = s.attach_mesh(level, floor_mesh(), collider{}); + val crate := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ 3, 0.5, 0 }) }); + val held := s.attach(crate, collider{ shape = shape::box(vec3{ 0.5, 0.5, 0.5 }), layers = 2 }); + var found: u32 = 0; + s.overlap(&shape::sphere(0.3), pose::of(vec3{ 2.4, 0.1, 0 }), 0xFFFFFFFF, def(c: collider_id, b: body_id): bool { + found++; + return true; + }); + t.expects(found == 2); + found = 0; + s.overlap(&shape::sphere(0.3), pose::of(vec3{ 2.4, 0.1, 0 }), 2, def(c: collider_id, b: body_id): bool { + found++; + return true; + }); + t.expects(found == 1); + # A ball cast down meets the floor's triangle; cast along it, the crate. + val ball := shape::sphere(0.25); + val down := s.shape_cast(&ball, pose::of(vec3{ -2.3, 3, 1.6 }), vec3{ 0, -5, 0 }) else { t.expects(false); return; }; + t.expects(near(down.point.y, 0, 1e-3) && near(down.normal.y, 1, 1e-3) && down.triangle != 0xFFFFFFFF); + val along := s.shape_cast(&ball, pose::of(vec3{ 0, 0.5, 0 }), vec3{ 10, 0, 0 }) else { t.expects(false); return; }; + t.expects(along.collider == held && near(along.point.x, 2.5, 0.01)); +} + +# A terrain of 33 by 33 heights a meter apart, of a slope and a bump. +def terrain(): heightfield { + var heights := vector::::new(); + for z in 0..33u { + for x in 0..33u { + val dx := x as f32 - 16; + val dz := z as f32 - 16; + heights.append(0.1 * x as f32 + 2 * math::exp(-(dx * dx + dz * dz) / 20)); + } + } + return heightfield::new(33, 33, heights.span); +} + +@test def keeps_heightfields(t: &mut tester): void { + val field := terrain(); + t.expects(field.length == 32 * 32 * 2); + # Its height between its heights is as its triangles lie. + val at := field.height_at(16, 16) else { t.expects(false); return; }; + t.expects(near(at, 1.6 + 2, 1e-4)); + val between := field.height_at(4.5, 2.25) else { t.expects(false); return; }; + t.expects(between > 0.4 && between < 0.5); + t.expects(!(field.height_at(-1, 3) is some(_))); + var s := space::new(); + val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ -16, 0, -16 }) }); + _ = s.attach_heightfield(ground, terrain(), collider{}); + # A ray down meets it where its height says. + val hit := s.ray_cast(vec3{ 0, 10, 0 }, vec3::down, 20) else { t.expects(false); return; }; + t.expects(near(hit.point.y, 3.6, 1e-3) && hit.normal.y > 0.9); + # A ball dropped by the bump rolls off it, down the slope, resting on the + # ground below, never sunk in it. + val ball := s.add(body{ at = pose::of(vec3{ 1.3, 5, 0.4 }) }); + _ = s.attach(ball, collider{ shape = shape::sphere(0.5), friction = 0.5 }); + var sunk := false; + for i in 0..300u { + s.step(1f / 60f); + val p := s.pose_of(ball).at; + if field.height_at(p.x + 16, p.z + 16) is some(h) { + if p.y < h + 0.3 { + sunk = true; + } + } + } + t.expects(!sunk && s.pose_of(ball).at.x > 3); +} + +@test def slides_along_sliders(t: &mut tester): void { + var s := space::new(); + val ground := s.add(body{ kind = body_kind::static }); + val block := s.add(body{ at = pose::of(vec3{ 0, 2, 0 }) }); + _ = s.attach(block, collider{ shape = shape::box(vec3{ 0.5, 0.25, 0.25 }) }); + val rail := s.slider(ground, block, vec3{ 0, 2, 0 }, vec3{ 1, 0, 1 }); + var made := s.joint_of(rail); + made.motor = true; + made.motor_speed = 2; + made.max_motor_force = 100; + made.limit = true; + made.lower = -1; + made.upper = 3; + s.change(rail, made); + run(&mut s, 3); + val at := s.pose_of(block); + val along := 3 / math::sqrt(2f); + t.expects(near(at.at.x, along, 0.03) && near(at.at.z, along, 0.03) && near(at.at.y, 2, 0.01)); + t.expects(near(at.turn.w, 1, 1e-3)); +} + +@test def limits_ball_joints_by_cone_and_twist(t: &mut tester): void { + var s := space::new(); + val post := s.add(body{ kind = body_kind::static }); + # An arm hanging from a shoulder held within 30 degrees of straight out, + # sideways, sags no further than its cone. + val arm := s.add(body{ at = pose::of(vec3{ 1, 3, 0 }) }); + _ = s.attach(arm, collider{ shape = shape::box(vec3{ 1, 0.1, 0.1 }) }); + _ = s.cone_twist(post, arm, vec3{ 0, 3, 0 }, vec3::right, math::pi as f32 / 6, 0.2); + run(&mut s, 3); + val tip := s.pose_of(arm).apply(vec3{ 1, 0, 0 }); + val sag := math::atan2(3 - tip.y, tip.x); + t.expects(near(sag, math::pi as f32 / 6, 0.03)); + # Spun about its length, it twists no further than its limit. + var twisty := space::new(vec3::zero); + val base := twisty.add(body{ kind = body_kind::static }); + val bar := twisty.add(body{ at = pose::of(vec3{ 1, 0, 0 }), spin = vec3{ 5, 0, 0 } }); + _ = twisty.attach(bar, collider{ shape = shape::box(vec3{ 1, 0.1, 0.3 }) }); + _ = twisty.cone_twist(base, bar, vec3::zero, vec3::right, 0.5, 0.4); + var most: f32 = 0; + for i in 0..120u { + twisty.step(1f / 60f); + val q := twisty.pose_of(bar).turn; + most = math::max(most, 2 * math::atan2(math::abs(q.x), math::abs(q.w))); + } + t.expects(most < 0.45 && most > 0.35); +} + +@test def holds_six_way_joints(t: &mut tester): void { + # Locked every way, it holds as a fixed joint: a beam out from a wall stays. + var s := space::new(); + val wall := s.add(body{ kind = body_kind::static }); + val beam := s.add(body{ at = pose::of(vec3{ 1, 2, 0 }) }); + _ = s.attach(beam, collider{ shape = shape::box(vec3{ 1, 0.1, 0.1 }) }); + val held := s.six_dof(wall, beam, vec3{ 0, 2, 0 }); + run(&mut s, 2); + t.expects(near(s.pose_of(beam).at.y, 2, 0.02) && near(s.pose_of(beam).turn.w, 1, 2e-3)); + # Its twist freed and driven, it turns about x as a hinge would; its swing + # about z limited, freed, it sags to its limit. + var made := s.joint_of(held); + made.holds[3] = axis_hold::free; + made.drives[3] = 2; + made.forces[3] = 200; + made.holds[5] = axis_hold::limited; + made.lows[5] = -0.3; + made.highs[5] = 0.3; + s.change(held, made); + run(&mut s, 2); + val turn := s.pose_of(beam).turn; + val tip := s.pose_of(beam).apply(vec3{ 1, 0, 0 }); + t.expects(near(s.spin_of(beam).x, 2, 0.2) && near(math::atan2(2 - tip.y, tip.x), 0.3, 0.04)); + # Its place freed along x, a slider: pulled by gravity along a slope. + var slope := space::new(); + val anchor := slope.add(body{ kind = body_kind::static }); + val car := slope.add(body{ at = pose::of(vec3{ 0, 2, 0 }) }); + _ = slope.attach(car, collider{ shape = shape::box(vec3{ 0.2, 0.2, 0.2 }) }); + val tilt := quat::axis_angle(vec3::back, -math::pi as f32 / 6); + val rail := slope.six_dof(anchor, car, vec3{ 0, 2, 0 }, tilt); + var free := slope.joint_of(rail); + free.holds[0] = axis_hold::free; + slope.change(rail, free); + run(&mut slope, 1); + val p := slope.pose_of(car).at; + t.expects(p.x > 1 && near((p.y - 2) / p.x, -math::tan(math::pi as f32 / 6), 0.02)); +} + +# A tower of crates and a ball thrown into it, stepped a second on so many +# threads, and where its top crate ends. +def toppled(threads: u32): pose { + var s := space::new(); + s.threads = threads; + val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ 0, -1, 0 }) }); + _ = s.attach(ground, collider{ shape = shape::box(vec3{ 50, 1, 50 }) }); + var top := body_id{}; + for i in 0..8u { + for j in 0..2u { + for k in 0..2u { + top = s.add(body{ at = pose::of(vec3{ j as f32 * 1.1, 0.5 + i as f32, k as f32 * 1.1 }) }); + _ = s.attach(top, collider{ shape = shape::box(vec3{ 0.5, 0.5, 0.5 }) }); + } + } + } + val ball := s.add(body{ at = pose::of(vec3{ -8, 3, 0.5 }), velocity = vec3{ 20, 0, 0 } }); + _ = s.attach(ball, collider{ shape = shape::sphere(0.4), density = 5 }); + run(&mut s, 1); + return s.pose_of(top); +} + +@test def solves_the_same_on_several_threads(t: &mut tester): void { + val one := toppled(1); + val four := toppled(4); + t.expects(one == four && one.at.x != 1.1f); +} diff --git a/tests/photometry.sakura b/tests/photometry.sakura new file mode 100644 index 0000000..c8935e5 --- /dev/null +++ b/tests/photometry.sakura @@ -0,0 +1,71 @@ +#! Contains the tests of `photometry`: lumens and candela of lights every way and +#! within cones, lux and nits of surfaces, exposure values and what they +#! multiply light by, and the colors of temperatures. + +import std::testing; +import std::math; +import malunal::linear; +import malunal::photometry; + +# Whether two numbers are within so much of one another, as a fraction of the +# greater: a hundred-thousandth, at first. +def close(a: f32, b: f32, within: f32 = 1e-5): bool { + return math::abs(a - b) <= within * math::max(math::abs(a), math::abs(b)); +} + +@test def converts_lumens_and_candela(t: &mut tester): void { + val pi := math::pi as f32; + # A sphere's solid angle, a hemisphere's, and a cone of 60 degrees each way. + t.expects(close(solid_angle_of(pi), 4 * pi) && close(solid_angle_of(pi / 2), 2 * pi) && close(solid_angle_of(pi / 3), pi)); + # A bare bulb's 800 lumens are about 63.7 candela every way; gathered into + # the cone of 60 degrees, about 255. + t.expects(close(candela_of_lumens(lumens::bulb_60w), 63.66198) && close(candela_of_lumens(800, pi / 3), 254.6479)); + t.expects(close(lumens_of_candela(candela::candle), lumens::candle) && close(lumens_of_candela(candela_of_lumens(300, 0.2), 0.2), 300)); + # An LED of 8 watts gives what a 60-watt incandescent bulb did. + t.expects(close(lumens_of_watts(8, efficacy::led), lumens::bulb_60w) && close(watts_of_lumens(lumens::bulb_60w, efficacy::incandescent), 57.14286)); +} + +@test def converts_lux_and_nits(t: &mut tester): void { + # A light of 100 candela gives a surface 2 meters away 25 lux, and gives 4 + # lux 5 meters away. + t.expects(close(lux_of_candela(100, 2), 25) && close(distance_of_lux(100, 4), 5)); + # A white surface lit by π lux gives back a nit; a grey one half as much. + t.expects(close(nits_of_lux(math::pi as f32), 1) && close(nits_of_lux(100, 0.5), 15.915494)); + t.expects(close(lux_of_nits(nits_of_lux(lux::office, 0.18), 0.18), lux::office)); + # A clear sky of 7,000 nits lights the ground with about 22,000 lux. + t.expects(close(lux_of_nits(nits::clear_sky), 21991.15)); +} + +@test def exposes_by_exposure_values(t: &mut tester): void { + # f/16 at a hundredth of a second, as the sunny 16 rule has it, at ISO 100, + # and a step less at ISO 200. + t.expects(close(ev100_of_camera(16, 0.01), 14.643856) && close(ev100_of_camera(16, 0.01, 200), 13.643856)); + t.expects(close(ev100_of_lux(lux::direct_sunlight), 15.287712) && close(ev100_of_nits(12.5), 6.643856)); + t.expects(close(exposure_of_ev100(0), 1.0 / 1.2) && close(exposure_of_ev100(1), 1.0 / 2.4)); + t.expects(close(ev100_of_exposure(exposure_of_ev100(9.7)), 9.7) && close(ev100_of_exposure(1), -0.2630344)); + # Exposed as a meter where it's lit reads, a white surface records as two + # thirds of the most, and an 18% grey card about an eighth: middle grey. + for light in [lux::full_moon, lux::office, lux::direct_sunlight] { + val exposure := exposure_of_ev100(ev100_of_lux(light)); + t.expects(close(nits_of_lux(light) * exposure, 0.6631456, 1e-4) && close(nits_of_lux(light, 0.18) * exposure, 0.1193662, 1e-4)); + } +} + +@test def colors_temperatures(t: &mut tester): void { + # A warm bulb's is orange, daylight's about white, and a blue sky's blue. + val warm := color_of_temperature(2700); + t.expects(warm.x == 1 && close(warm.y, 0.4159, 1e-3) && close(warm.z, 0.0984, 1e-2)); + val day := color_of_temperature(6500); + t.expects(day.x == 1 && day.y > 0.93 && day.z > 0.98); + val sky := color_of_temperature(10000); + t.expects(sky.z == 1 && sky.y > sky.x && close(sky.x, 0.6095, 1e-3)); + # Hotter is bluer all the way. + var last := color_of_temperature(1000); + for k in 1..40u { + val next := color_of_temperature(1000 * (k + 1) as f32); + t.expects(next.z / next.x >= last.z / last.x); + last = next; + } + # Past either end, as either. + t.expects(color_of_temperature(500) == color_of_temperature(1000) && color_of_temperature(90000) == color_of_temperature(40000)); +} diff --git a/tests/physics2d.sakura b/tests/physics2d.sakura new file mode 100644 index 0000000..8d3b656 --- /dev/null +++ b/tests/physics2d.sakura @@ -0,0 +1,301 @@ +#! Contains the tests of `physics2d`: rotations and poses; shapes, their boxes, +#! and what they hold; manifolds between circles, capsules, and polygons, a +#! box resting on another at two points, a corner at one; rays meeting each +#! shape; a tree of boxes, sound as it's changed, finding what a brute search +#! finds; and a grid of solid cells, met but for the faces they share, and +#! rays passing through it. + +import std::testing; +import std::containers; +import std::math; +import malunal::linear; +import malunal::physics2d; + +# Whether two numbers are within a hundred-thousandth or so of one another. +def near(a: f32, b: f32): bool { + return math::abs(a - b) < 1e-4; +} + +def near(a: vec2, b: vec2): bool { + return near(a.x, b.x) && near(a.y, b.y); +} + +@test def turns_and_places_by_poses(t: &mut tester): void { + val quarter := rot::of(math::pi as f32 / 2); + t.expects(near(quarter.apply(vec2{ 1, 0 }), vec2{ 0, 1 }) && near(quarter.unapply(vec2{ 0, 1 }), vec2{ 1, 0 })); + t.expects(near(quarter.angle, math::pi as f32 / 2) && near((quarter * quarter).apply(vec2{ 1, 0 }), vec2{ -1, 0 })); + val at := pose::of(vec2{ 3, 1 }, math::pi as f32 / 2); + t.expects(near(at.apply(vec2{ 1, 0 }), vec2{ 3, 2 }) && near(at.unapply(vec2{ 3, 2 }), vec2{ 1, 0 })); + # A pose within another, and found again within it. + val inner := pose::of(vec2{ -2, 0.5 }, 0.7); + val both := at * inner; + t.expects(near(both.apply(vec2{ 1, 1 }), at.apply(inner.apply(vec2{ 1, 1 })))); + val found := at.unapply_pose(both); + t.expects(near(found.at, inner.at) && near(found.turn.angle, 0.7)); +} + +@test def makes_shapes(t: &mut tester): void { + # A box's corners counterclockwise from its bottom left, each edge's normal + # facing out. + val box := shape::box(vec2{ 2, 1 }); + t.expects(box.kind == shape_kind::polygon && box.count == 4 && near(box.point(0), vec2{ -2, -1 }) && near(box.point(2), vec2{ 2, 1 })); + t.expects(near(box.normal(0), vec2{ 0, -1 }) && near(box.normal(1), vec2{ 1, 0 }) && near(box.normal(2), vec2{ 0, 1 }) && near(box.normal(3), vec2{ -1, 0 })); + # A polygon around places leaves out what's within and along its edges. + val places: vec2[7] = [vec2{ 0, 0 }, vec2{ 2, 0 }, vec2{ 1, 0 }, vec2{ 2, 2 }, vec2{ 1, 1 }, vec2{ 0, 2 }, vec2{ 0, 2 }]; + val square := shape::polygon(places[:]).expect("A square is made."); + t.expects(square.count == 4 && square.contains(pose::identity, vec2{ 1, 1 }) && !square.contains(pose::identity, vec2{ 2.1, 1 })); + # A line holds no area, and nine corners are too many. + val line: vec2[3] = [vec2{ 0, 0 }, vec2{ 1, 1 }, vec2{ 2, 2 }]; + t.expects(shape::polygon(line[:]) is none); + var round := vector::::new(); + for i in 0..9u { + round.append(rot::of(i as f32 * 2 * math::pi as f32 / 9).apply(vec2{ 1, 0 })); + } + t.expects(shape::polygon(round.span) is none); + # A capsule of one place is a circle; a pill stands up. + t.expects(shape::capsule(vec2{ 1, 1 }, vec2{ 1, 1 }, 0.5).kind == shape_kind::circle); + val pill := shape::pill(1, 3); + t.expects(pill.kind == shape_kind::capsule && near(pill.point(0), vec2{ 0, -1 }) && near(pill.point(1), vec2{ 0, 1 }) && near(pill.radius, 0.5)); + # The box holding a shape where a pose places it. + val turned := box.bounds(pose::of(vec2{ 10, 0 }, math::pi as f32 / 2)); + t.expects(near(turned.min, vec2{ 9, -2 }) && near(turned.max, vec2{ 11, 2 })); + val held := pill.bounds(pose::of(vec2{ 0, 5 })); + t.expects(near(held.min, vec2{ -0.5, 3.5 }) && near(held.max, vec2{ 0.5, 6.5 })); + t.expects(pill.contains(pose::identity, vec2{ 0.4, 1.2 }) && !pill.contains(pose::identity, vec2{ 0.45, 1.4 })); +} + +@test def collides_circles_and_hulls(t: &mut tester): void { + val ball := shape::circle(0.5); + val other := shape::circle(1); + val met := collide(&ball, pose::identity, &other, pose::of(vec2{ 1.2, 0 })).expect("They meet."); + t.expects(met.count == 1 && near(met.normal, vec2{ 1, 0 }) && near(met.points[0].depth, 0.3) && near(met.points[0].point, vec2{ 0.35, 0 })); + t.expects(collide(&ball, pose::identity, &other, pose::of(vec2{ 1.6, 0 })) is none); + # Touching, they meet, at a depth of 0. + t.expects(collide(&ball, pose::identity, &other, pose::of(vec2{ 1.5, 0 })) is some(m) && near(m.depth, 0)); + + # A ball over a box's face, by its corner, and within it. + val slab := shape::box(vec2{ 1, 0.5 }); + val above := collide(&slab, pose::identity, &ball, pose::of(vec2{ 0, 0.9 })).expect("It rests on the box."); + t.expects(near(above.normal, vec2{ 0, 1 }) && near(above.depth, 0.1) && near(above.points[0].point, vec2{ 0, 0.45 })); + val corner := collide(&slab, pose::identity, &ball, pose::of(vec2{ 1.3, 0.8 })).expect("It meets the corner."); + val diagonal := math::sqrt(0.5f); + t.expects(near(corner.normal, vec2{ diagonal, diagonal }) && near(corner.depth, 0.5 - math::sqrt(0.18f))); + val small := shape::circle(0.1); + val within := collide(&slab, pose::identity, &small, pose::of(vec2{ 0.8, 0 })).expect("It's within the box."); + t.expects(near(within.normal, vec2{ 1, 0 }) && near(within.depth, 0.3)); + # The other way around, the normal is turned around. + val back := collide(&small, pose::of(vec2{ 0.8, 0 }), &slab, pose::identity).expect("It's within the box."); + t.expects(near(back.normal, vec2{ -1, 0 }) && near(back.depth, 0.3)); + # A capsule and a ball meet as the ball nears its segment. + val pill := shape::capsule(vec2{ -1, 0 }, vec2{ 1, 0 }, 0.25); + val side := collide(&pill, pose::identity, &ball, pose::of(vec2{ 0.3, 0.7 })).expect("It meets the capsule's side."); + t.expects(near(side.normal, vec2{ 0, 1 }) && near(side.depth, 0.05)); +} + +@test def collides_hulls_at_one_point_or_two(t: &mut tester): void { + # A box resting flat on another meets it at two points, midway between their + # surfaces. + val slab := shape::box(vec2{ 1, 0.5 }); + val crate := shape::box(vec2{ 0.5, 0.5 }); + val resting := collide(&slab, pose::identity, &crate, pose::of(vec2{ 0, 0.9 })).expect("The crate rests on the slab."); + t.expects(resting.count == 2 && near(resting.normal, vec2{ 0, 1 })); + t.expects(near(resting.points[0].depth, 0.1) && near(resting.points[1].depth, 0.1)); + t.expects(near(resting.points[0].point.y, 0.45) && near(math::abs(resting.points[0].point.x), 0.5) && near(resting.points[0].point.x, -resting.points[1].point.x)); + t.expects(collide(&slab, pose::identity, &crate, pose::of(vec2{ 0, 1.1 })) is none); + val flipped := collide(&crate, pose::of(vec2{ 0, 0.9 }), &slab, pose::identity).expect("The slab is under the crate."); + t.expects(flipped.count == 2 && near(flipped.normal, vec2{ 0, -1 })); + # A crate turned onto its corner meets the slab at the corner alone. + val tipped := collide(&slab, pose::identity, &crate, pose::of(vec2{ 0, 1.2 }, math::pi as f32 / 4)).expect("Its corner meets the slab."); + t.expects(tipped.count == 1 && near(tipped.normal, vec2{ 0, 1 }) && near(tipped.depth, 0.5 * math::sqrt(2f) - 0.7)); + + # A capsule lying on the slab meets it at two points; one standing by its + # corner, at one, along the line from the corner to its end. + val lying := shape::capsule(vec2{ -0.5, 0 }, vec2{ 0.5, 0 }, 0.5); + val flat := collide(&slab, pose::identity, &lying, pose::of(vec2{ 0, 0.9 })).expect("The capsule lies on the slab."); + t.expects(flat.count == 2 && near(flat.normal, vec2{ 0, 1 }) && near(flat.points[0].depth, 0.1) && near(flat.points[0].point.y, 0.45)); + val standing := shape::capsule(vec2{ 0, 0 }, vec2{ 0, 1 }, 0.5); + val by := collide(&slab, pose::identity, &standing, pose::of(vec2{ 1.3, 0.8 })).expect("The capsule's end meets the corner."); + val diagonal := math::sqrt(0.5f); + t.expects(by.count == 1 && near(by.normal, vec2{ diagonal, diagonal }) && near(by.depth, 0.5 - math::sqrt(0.18f))); + t.expects(!overlaps(&slab, pose::identity, &standing, pose::of(vec2{ 1.4, 0.9 }))); + # Two capsules side by side, and crossing. + val beside := collide(&lying, pose::identity, &lying, pose::of(vec2{ 0, 0.8 })).expect("They lie together."); + t.expects(near(beside.normal, vec2{ 0, 1 }) && near(beside.depth, 0.2)); + t.expects(overlaps(&lying, pose::identity, &lying, pose::of(vec2{ 0, 0 }, 1.2))); + # A segment, of no thickness, across a box. + val wire := shape::segment(vec2{ -2, 0 }, vec2{ 2, 0 }); + t.expects(overlaps(&wire, pose::identity, &crate, pose::of(vec2{ 0, 0.3 })) && !overlaps(&wire, pose::identity, &crate, pose::of(vec2{ 0, 0.6 }))); +} + +@test def casts_rays_at_shapes(t: &mut tester): void { + val up := vec2{ 0, 1 }; + val ball := shape::circle(1); + val struck := ball.ray_cast(pose::of(vec2{ 3, 0 }), vec2::zero, vec2{ 1, 0 }, 10).expect("It meets the ball."); + t.expects(near(struck.distance, 2) && near(struck.point, vec2{ 2, 0 }) && near(struck.normal, vec2{ -1, 0 })); + t.expects(ball.ray_cast(pose::of(vec2{ 3, 0 }), vec2::zero, up, 10) is none); + t.expects(ball.ray_cast(pose::of(vec2{ 3, 0 }), vec2::zero, vec2{ 1, 0 }, 1.5) is none); + val inside := ball.ray_cast(pose::of(vec2{ 3, 0 }), vec2{ 3, 0 }, up, 10).expect("It begins within the ball."); + t.expects(inside.distance == 0 && near(inside.normal, vec2{ 0, -1 })); + + # A box, turned a quarter, its long side up and down. + val box := shape::box(vec2{ 1, 0.5 }); + val roof := box.ray_cast(pose::of(vec2{ 0, 5 }, math::pi as f32 / 2), vec2::zero, up, 10).expect("It meets the box."); + t.expects(near(roof.distance, 4) && near(roof.normal, vec2{ 0, -1 }) && near(roof.point, vec2{ 0, 4 })); + t.expects(box.ray_cast(pose::of(vec2{ 0, 5 }), vec2::zero, up, 4) is none); + t.expects(box.ray_cast(pose::of(vec2{ 0, 5 }), vec2{ 2, 0 }, up, 10) is none); + + # A capsule, by its side and its round end. + val pill := shape::capsule(vec2{ -1, 3 }, vec2{ 1, 3 }, 0.5); + val side := pill.ray_cast(pose::identity, vec2::zero, up, 10).expect("It meets the capsule's side."); + t.expects(near(side.distance, 2.5) && near(side.normal, vec2{ 0, -1 })); + val end := pill.ray_cast(pose::identity, vec2{ 3, 3 }, vec2{ -1, 0 }, 10).expect("It meets the capsule's end."); + t.expects(near(end.distance, 1.5) && near(end.normal, vec2{ 1, 0 })); + # A segment, from either side. + val wire := shape::segment(vec2{ -1, 2 }, vec2{ 1, 2 }); + val from_below := wire.ray_cast(pose::identity, vec2::zero, up, 10).expect("It meets the segment from below."); + val from_above := wire.ray_cast(pose::identity, vec2{ 0, 5 }, vec2{ 0, -1 }, 10).expect("It meets the segment from above."); + t.expects(near(from_below.distance, 2) && near(from_below.normal, vec2{ 0, -1 }) && near(from_above.distance, 3) && near(from_above.normal, up)); +} + +# Numbers from 0 to 1, each of the last, as an LCG makes them. +struct dice { + var state: u64; +} + +def dice::next(&mut this): f32 { + this.state = math::wrapping_add(math::wrapping_mul(this.state, 6364136223846793005), 1442695040888963407); + return (this.state >> 40) as f32 / (1u << 24) as f32; +} + +# A box somewhere within 100 of the origin, as large as 3. +def some_box(seed: &mut dice): aabb { + val at := vec2{ seed.next() * 200 - 100, seed.next() * 200 - 100 }; + return aabb::around(at, vec2{ 0.1 + seed.next() * 1.4, 0.1 + seed.next() * 1.4 }); +} + +@test def sorts_boxes_in_a_tree(t: &mut tester): void { + var seed := dice{ state = 7 }; + var tree := aabb_tree::new(0.25); + var boxes := vector::::new(); + var leaves := vector::::new(); + for i in 0..500u { + val box := some_box(&mut seed); + boxes.append(box); + leaves.append(tree.insert(box, i)); + } + t.expects(tree.length == 500 && tree.is_sound() && tree.height <= 18); + + # Moved a little, a leaf stays; moved further, it's put again. Half are + # removed. + t.expects(!tree.move(leaves[0], aabb{ boxes[0].min + vec2{ 0.1, 0 }, boxes[0].max + vec2{ 0.1, 0 } })); + for i in 0..500u { + if i % 2 == 0 { + boxes[i] = some_box(&mut seed); + _ = tree.move(leaves[i], boxes[i]); + } else if i % 4 == 1 { + tree.remove(leaves[i]); + } + } + t.expects(tree.length == 375 && tree.is_sound()); + + # What a box meets is what a brute search finds, of the leaves' grown boxes. + for k in 0..20u { + val asked := aabb::around(vec2{ seed.next() * 200 - 100, seed.next() * 200 - 100 }, vec2{ 8, 8 }); + var found := vector::::new(); + tree.query(asked, def(leaf: u32, data: u64): bool { + found.append(data); + return true; + }); + var expected: u64 = 0; + for i in 0..500u { + if i % 4 != 1 && tree.box_of(leaves[i]).overlaps(asked) { + expected++; + } + } + t.expects(found.length == expected); + } + + # The nearest box along a ray, the search narrowing as each is met. + val from := vec2{ -120, 3 }; + val way := vec2{ 1, 0.1 }.normalized(); + var nearest: f32 = 1000; + tree.ray_cast(from, way, 1000, def(leaf: u32, data: u64, reach: f32): f32 { + if boxes[data].ray_hit(from, way, reach) is some(at) { + nearest = math::min(nearest, at); + return at; + } + return reach; + }); + var expected: f32 = 1000; + for i in 0..500u { + if i % 4 != 1 && boxes[i].ray_hit(from, way, 1000) is some(at) { + expected = math::min(expected, at); + } + } + t.expects(near(nearest, expected) && expected < 1000); + for i in 0..500u { + if i % 4 != 1 { + tree.remove(leaves[i]); + } + } + t.expects(tree.length == 0 && tree.is_sound() && tree.height == 0); +} + +# Six cells across and four up: a floor along the bottom, and a wall up the +# right side. +def walled(): grid { + var made := grid::new(6, 4); + for x in 0..6u { + made.set(x as u32, 0, true); + } + for y in 0..4u { + made.set(5, y as u32, true); + } + return made; +} + +# The manifolds a shape meets a grid with. +def met(g: &grid, at: pose, s: &shape, at_s: pose): vector { + var found := vector::::new(); + g.collide(at, s, at_s, def(x: u32, y: u32, m: manifold): bool { + found.append(m); + return true; + }); + return found; +} + +@test def meets_a_grid_of_solid_cells(t: &mut tester): void { + val g := walled(); + t.expects(g.is_solid(2, 0) && !g.is_solid(2, 1) && g.is_solid(5, 3) && !g.is_solid(-1, 0) && !g.is_solid(6, 0)); + val crate := shape::box(vec2{ 0.4, 0.4 }); + # On the floor, across two cells, pushed up by both. + val resting := met(&g, pose::identity, &crate, pose::of(vec2{ 2, 1.35 })); + t.expects(resting.length == 2 && near(resting[0].normal, vec2{ 0, 1 }) && near(resting[1].normal, vec2{ 0, 1 }) && near(resting[0].depth, 0.05)); + # Sunk into the floor and just over a seam: the cell past the seam would + # push it back across the floor, along the face two cells share, so it's + # passed over. + val sunk := met(&g, pose::identity, &crate, pose::of(vec2{ 1.61, 0.75 })); + t.expects(sunk.length == 1 && near(sunk[0].normal, vec2{ 0, 1 }) && near(sunk[0].depth, 0.65)); + # Against the wall, pushed back from it. + val leaning := met(&g, pose::identity, &crate, pose::of(vec2{ 4.65, 2 })); + t.expects(leaning.length == 2 && near(leaning[0].normal, vec2{ -1, 0 }) && near(leaning[0].depth, 0.05)); + t.expects(g.overlaps(pose::identity, &crate, pose::of(vec2{ 4.65, 2 })) && !g.overlaps(pose::identity, &crate, pose::of(vec2{ 2, 2 }))); + # The grid placed elsewhere is met there. + val moved := pose::of(vec2{ 10, 0 }); + t.expects(met(&g, moved, &crate, pose::of(vec2{ 12, 1.35 })).length == 2 && met(&g, moved, &crate, pose::of(vec2{ 2, 1.35 })).empty); + + # A ray down to the floor, through the cells above it. + val down := vec2{ 1, -1 }.normalized(); + val floor := g.ray_cast(pose::identity, vec2{ 0.3, 3.5 }, down, 10).expect("It meets the floor."); + t.expects(floor.x == 2 && floor.y == 0 && near(floor.hit.distance, 2.5 * math::sqrt(2f)) && near(floor.hit.normal, vec2{ 0, 1 })); + t.expects(near(floor.hit.point, vec2{ 2.8, 1 })); + # From outside the grid, into the wall. + val wall := g.ray_cast(pose::identity, vec2{ -2, 2.5 }, vec2{ 1, 0 }, 10).expect("It meets the wall."); + t.expects(wall.x == 5 && wall.y == 2 && near(wall.hit.distance, 7) && near(wall.hit.normal, vec2{ -1, 0 })); + t.expects(g.ray_cast(pose::identity, vec2{ -2, 2.5 }, vec2{ 1, 0 }, 6.5) is none); + t.expects(g.ray_cast(pose::identity, vec2{ 1, 2 }, vec2{ 0, 1 }, 10) is none); + val within := g.ray_cast(pose::identity, vec2{ 5.5, 2.5 }, vec2{ -1, 0 }, 10).expect("It begins in the wall."); + t.expects(within.hit.distance == 0 && within.x == 5 && within.y == 2); + val there := g.ray_cast(moved, vec2{ 8, 2.5 }, vec2{ 1, 0 }, 10).expect("It meets the moved wall."); + t.expects(near(there.hit.distance, 7) && near(there.hit.point, vec2{ 15, 2.5 })); +} diff --git a/tests/physics3d.sakura b/tests/physics3d.sakura new file mode 100644 index 0000000..9fb3eb7 --- /dev/null +++ b/tests/physics3d.sakura @@ -0,0 +1,640 @@ +#! Contains the tests of `physics3d`: poses; hulls of boxes, of places, and of +#! triangles, their faces facing out; shapes, their boxes, and what they hold; +#! manifolds between spheres, capsules, and hulls, a box resting on another at +#! four points, on its edge at two, on its corner at one, and edge across edge +#! at one; rays meeting each shape; a tree of boxes, sound as it's changed, +#! finding what a brute search finds; and a mesh of triangles, met but for the +#! edges its triangles share flat, and rays meeting it. + +import std::testing; +import std::containers; +import std::math; +import malunal::geometry; +import malunal::linear; +import malunal::physics3d; + +# Whether two numbers are within a hundred-thousandth or so of one another. +def near(a: f32, b: f32): bool { + return math::abs(a - b) < 1e-4; +} + +def near(a: vec3, b: vec3): bool { + return near(a.x, b.x) && near(a.y, b.y) && near(a.z, b.z); +} + +def quarter_about(axis: vec3): quat { + return quat::axis_angle(axis, math::pi as f32 / 2); +} + +@test def turns_and_places_by_poses(t: &mut tester): void { + # x turned a quarter about y, counterclockwise as y points at the viewer, is + # -z. + val at := pose::of(vec3{ 3, 1, 0 }, quarter_about(vec3::up)); + t.expects(near(at.apply(vec3{ 1, 0, 0 }), vec3{ 3, 1, -1 }) && near(at.unapply(vec3{ 3, 1, -1 }), vec3{ 1, 0, 0 })); + t.expects(near(at.rotate(vec3{ 1, 0, 0 }), vec3{ 0, 0, -1 }) && near(at.unrotate(vec3{ 0, 0, -1 }), vec3{ 1, 0, 0 })); + # A pose within another, found again within it, and undone. + val inner := pose::of(vec3{ -2, 0.5, 1 }, quat::axis_angle(vec3{ 1, 1, 0 }, 0.7)); + val both := at * inner; + val p := vec3{ 1, 2, 3 }; + t.expects(near(both.apply(p), at.apply(inner.apply(p)))); + val found := at.unapply_pose(both); + t.expects(near(found.at, inner.at) && near(found.apply(p), inner.apply(p))); + t.expects(near(at.inverse().apply(at.apply(p)), p) && near((at * at.inverse()).apply(p), p)); +} + +# Each face's corners on its plane, counterclockwise about its normal, and +# every corner of the hull behind it. +def faces_out(h: &hull): bool { + for f in 0..h.faces { + val n := h.normal(f); + val offset := h.offset(f); + return false if !near(n.length, 1); + val size := h.face_size(f); + for k in 0..size { + val a := h.point(h.corner(f, k)); + val b := h.point(h.corner(f, (k + 1) % size)); + val c := h.point(h.corner(f, (k + 2) % size)); + return false if !near(n.dot(a), offset) || (b - a).cross(c - b).dot(n) < -1e-4; + } + for i in 0..h.count { + return false if n.dot(h.point(i)) > offset + 1e-4; + } + } + return true; +} + +@test def makes_hulls(t: &mut tester): void { + # A box's faces, +x, -x, +y, -y, +z, and -z, each edge between two at right + # angles. + val box := hull::box(vec3{ 2, 1, 0.5 }); + t.expects(box.count == 8 && box.faces == 6 && box.edges == 12 && faces_out(&box) && !box.is_flat); + t.expects(near(box.normal(0), vec3{ 1, 0, 0 }) && near(box.offset(0), 2) && near(box.normal(3), vec3{ 0, -1, 0 }) && near(box.offset(4), 0.5)); + var square := true; + for e in 0..box.edges { + val sides := box.edge_faces(e); + square = square && sides[0] != sides[1] && near(box.normal(sides[0]).dot(box.normal(sides[1])), 0); + } + t.expects(square && box.point(box.support(vec3{ 1, 1, 1 })) == vec3{ 2, 1, 0.5 }); + # Turned and moved, its faces still face out. + val turned := hull::box(vec3{ 2, 1, 0.5 }, vec3{ 5, 0, 0 }, quat::axis_angle(vec3{ 1, 2, 3 }, 0.9)); + t.expects(faces_out(&turned) && near(turned.center, vec3{ 5, 0, 0 })); + + # Around a cube's corners, with places within it, on its faces, and along + # its edges: its 8 corners, 6 square faces, and 12 edges. + val places: vec3[12] = [ + vec3{ 0.3, -0.2, 0.5 }, vec3{ -1, -1, -1 }, vec3{ 1, -1, -1 }, vec3{ -1, 1, -1 }, vec3{ 1, 1, -1 }, vec3{ 0, 0, 0 }, + vec3{ -1, -1, 1 }, vec3{ 1, -1, 1 }, vec3{ -1, 1, 1 }, vec3{ 1, 1, 1 }, vec3{ 1, 0, 0 }, vec3{ 1, 1, 0 }, + ]; + val cube := hull::of(places[:]).expect("A cube is made."); + t.expects(cube.count == 8 && cube.faces == 6 && cube.edges == 12 && faces_out(&cube)); + var quads := true; + for f in 0..cube.faces { + quads = quads && cube.face_size(f) == 4; + } + t.expects(quads && near(cube.center, vec3::zero)); + # A tetrahedron, and an icosahedron's 12 corners, of 20 triangles. + val corners: vec3[4] = [vec3{ 0, 0, 0 }, vec3{ 1, 0, 0 }, vec3{ 0, 1, 0 }, vec3{ 0, 0, 1 }]; + val tetrahedron := hull::of(corners[:]).expect("A tetrahedron is made."); + t.expects(tetrahedron.count == 4 && tetrahedron.faces == 4 && tetrahedron.edges == 6 && faces_out(&tetrahedron)); + val phi := (1 + math::sqrt(5f)) / 2; + var ico := vector::::new(); + for i in 0..4u { + val a: f32 = (i & 1) != 0 ? 1 : -1; + val b: f32 = (i & 2) != 0 ? phi : -phi; + ico.append(vec3{ 0, a, b }); + ico.append(vec3{ a, b, 0 }); + ico.append(vec3{ b, 0, a }); + } + val twenty := hull::of(ico.span).expect("An icosahedron is made."); + t.expects(twenty.count == 12 && twenty.faces == 20 && twenty.edges == 30 && faces_out(&twenty)); + + # Flat places hold no volume, and 40 corners are too many. + val flat: vec3[5] = [vec3{ 0, 0, 0 }, vec3{ 1, 0, 0 }, vec3{ 1, 1, 0 }, vec3{ 0, 1, 0 }, vec3{ 0.5, 0.5, 0 }]; + t.expects(hull::of(flat[:]) is none && hull::of(corners[0:3]) is none); + var ball := vector::::new(); + for i in 0..40u { + val y := 1 - 2 * (i as f32 + 0.5) / 40; + val r := math::sqrt(1 - y * y); + val theta := i as f32 * 2.39996; + ball.append(vec3{ r * math::cos(theta), y, r * math::sin(theta) }); + } + t.expects(hull::of(ball.span) is none); + + # A triangle is flat: a face each way, and each edge between them. + val triangle := hull::triangle(vec3{ 0, 0, 0 }, vec3{ 1, 0, 0 }, vec3{ 0, 0, -1 }); + t.expects(triangle.is_flat && triangle.count == 3 && triangle.faces == 2 && triangle.edges == 3); + t.expects(near(triangle.normal(0), vec3{ 0, 1, 0 }) && near(triangle.normal(1), vec3{ 0, -1, 0 })); +} + +@test def makes_shapes(t: &mut tester): void { + t.expects(shape::capsule(vec3{ 1, 1, 1 }, vec3{ 1, 1, 1 }, 0.5).kind == shape_kind::sphere); + val pill := shape::pill(1, 3); + t.expects(pill.kind == shape_kind::capsule && near(pill.a, vec3{ 0, -1, 0 }) && near(pill.b, vec3{ 0, 1, 0 }) && near(pill.radius, 0.5)); + # The box holding a shape where a pose places it. + val box := shape::box(vec3{ 2, 1, 0.5 }); + val turned := box.bounds(pose::of(vec3{ 10, 0, 0 }, quarter_about(vec3::back))); + t.expects(near(turned.min, vec3{ 9, -2, -0.5 }) && near(turned.max, vec3{ 11, 2, 0.5 })); + val held := pill.bounds(pose::of(vec3{ 0, 5, 0 })); + t.expects(near(held.min, vec3{ -0.5, 3.5, -0.5 }) && near(held.max, vec3{ 0.5, 6.5, 0.5 })); + # What they hold. + t.expects(pill.contains(pose::identity, vec3{ 0.4, 1.2, 0 }) && !pill.contains(pose::identity, vec3{ 0.45, 1.4, 0 })); + t.expects(box.contains(pose::identity, vec3{ 1.9, 0.9, 0.4 }) && !box.contains(pose::identity, vec3{ 2.1, 0, 0 })); + t.expects(box.contains(pose::of(vec3{ 10, 0, 0 }, quarter_about(vec3::back)), vec3{ 10.9, 1.9, 0 })); + t.expects(shape::hull_of(corners_of_cube()[:]) is some(s) && s.kind == shape_kind::hull); +} + +def corners_of_cube(): vec3[8] { + return [ + vec3{ -1, -1, -1 }, vec3{ 1, -1, -1 }, vec3{ -1, 1, -1 }, vec3{ 1, 1, -1 }, + vec3{ -1, -1, 1 }, vec3{ 1, -1, 1 }, vec3{ -1, 1, 1 }, vec3{ 1, 1, 1 }, + ]; +} + +@test def collides_spheres_and_capsules(t: &mut tester): void { + val ball := shape::sphere(0.5); + val other := shape::sphere(1); + val met := collide(&ball, pose::identity, &other, pose::of(vec3{ 1.2, 0, 0 })).expect("They meet."); + t.expects(met.count == 1 && near(met.normal, vec3{ 1, 0, 0 }) && near(met.points[0].depth, 0.3) && near(met.points[0].point, vec3{ 0.35, 0, 0 })); + t.expects(collide(&ball, pose::identity, &other, pose::of(vec3{ 1.6, 0, 0 })) is none); + t.expects(collide(&ball, pose::identity, &other, pose::of(vec3{ 1.5, 0, 0 })) is some(m) && near(m.depth, 0)); + # Within a margin, apart, at a depth below 0. + t.expects(collide(&ball, pose::identity, &other, pose::of(vec3{ 1.6, 0, 0 }), 0.2) is some(m) && near(m.depth, -0.1)); + + # Capsules lying along one another meet at two points; crossing, at one. + val lying := shape::capsule(vec3{ -0.5, 0, 0 }, vec3{ 0.5, 0, 0 }, 0.5); + val beside := collide(&lying, pose::identity, &lying, pose::of(vec3{ 0.2, 0.8, 0 })).expect("They lie together."); + t.expects(beside.count == 2 && near(beside.normal, vec3{ 0, 1, 0 }) && near(beside.points[0].depth, 0.2) && near(beside.points[1].depth, 0.2)); + t.expects(near(beside.points[0].point, vec3{ -0.3, 0.4, 0 }) && near(beside.points[1].point, vec3{ 0.5, 0.4, 0 })); + val crossing := collide(&lying, pose::identity, &lying, pose::of(vec3{ 0, 0.8, 0 }, quarter_about(vec3::up))).expect("They cross."); + t.expects(crossing.count == 1 && near(crossing.normal, vec3{ 0, 1, 0 }) && near(crossing.depth, 0.2) && near(crossing.points[0].point, vec3{ 0, 0.4, 0 })); + # A ball by a capsule's side. + val pill := shape::capsule(vec3{ -1, 0, 0 }, vec3{ 1, 0, 0 }, 0.25); + val side := collide(&pill, pose::identity, &ball, pose::of(vec3{ 0.3, 0, 0.7 })).expect("It meets the capsule's side."); + t.expects(near(side.normal, vec3{ 0, 0, 1 }) && near(side.depth, 0.05)); +} + +@test def collides_spheres_and_capsules_with_hulls(t: &mut tester): void { + val slab := shape::box(vec3{ 1, 0.5, 1 }); + val ball := shape::sphere(0.5); + # On the box's face, by its edge, by its corner, and within it. + val above := collide(&slab, pose::identity, &ball, pose::of(vec3{ 0, 0.9, 0 })).expect("It rests on the box."); + t.expects(near(above.normal, vec3{ 0, 1, 0 }) && near(above.depth, 0.1) && near(above.points[0].point, vec3{ 0, 0.45, 0 })); + val edge := collide(&slab, pose::identity, &ball, pose::of(vec3{ 1.3, 0.8, 0 })).expect("It meets the edge."); + val diagonal := math::sqrt(0.5f); + t.expects(near(edge.normal, vec3{ diagonal, diagonal, 0 }) && near(edge.depth, 0.5 - math::sqrt(0.18f))); + val corner := collide(&slab, pose::identity, &ball, pose::of(vec3{ 1.2, 0.7, 1.2 })).expect("It meets the corner."); + val third := math::sqrt(1f / 3f); + t.expects(near(corner.normal, vec3{ third, third, third }) && near(corner.depth, 0.5 - math::sqrt(0.12f))); + t.expects(collide(&slab, pose::identity, &ball, pose::of(vec3{ 1.3, 0.8, 1.3 })) is none); + val small := shape::sphere(0.1); + val within := collide(&slab, pose::identity, &small, pose::of(vec3{ 0.8, 0, 0 })).expect("It's within the box."); + t.expects(near(within.normal, vec3{ 1, 0, 0 }) && near(within.depth, 0.3)); + val back := collide(&small, pose::of(vec3{ 0.8, 0, 0 }), &slab, pose::identity).expect("It's within the box."); + t.expects(near(back.normal, vec3{ -1, 0, 0 }) && near(back.depth, 0.3)); + # The box turned, the ball over its face. + val tilted := collide(&slab, pose::of(vec3::zero, quarter_about(vec3::back)), &ball, pose::of(vec3{ -0.9, 0, 0 })).expect("It meets the turned box."); + t.expects(near(tilted.normal, vec3{ -1, 0, 0 }) && near(tilted.depth, 0.1)); + + # A capsule lying on the box meets it at two points; standing by its edge, + # at one; and stood within it, by the face it's nearest. + val lying := shape::capsule(vec3{ -0.5, 0, 0 }, vec3{ 0.5, 0, 0 }, 0.5); + val flat := collide(&slab, pose::identity, &lying, pose::of(vec3{ 0, 0.9, 0 })).expect("The capsule lies on the box."); + t.expects(flat.count == 2 && near(flat.normal, vec3{ 0, 1, 0 }) && near(flat.points[0].depth, 0.1) && near(flat.points[0].point.y, 0.45)); + val standing := shape::capsule(vec3{ 0, 0, 0 }, vec3{ 0, 1, 0 }, 0.5); + val by := collide(&slab, pose::identity, &standing, pose::of(vec3{ 1.3, 0.8, 0 })).expect("The capsule's end meets the edge."); + t.expects(by.count == 1 && near(by.normal, vec3{ diagonal, diagonal, 0 }) && near(by.depth, 0.5 - math::sqrt(0.18f))); + t.expects(!overlaps(&slab, pose::identity, &standing, pose::of(vec3{ 1.4, 0.9, 0 }))); + val stood := collide(&slab, pose::identity, &standing, pose::of(vec3{ 0, 0.3, 0 })).expect("The capsule stands within the box."); + t.expects(stood.count == 1 && near(stood.normal, vec3{ 0, 1, 0 }) && near(stood.depth, 0.7) && near(stood.points[0].point, vec3{ 0, 0.15, 0 })); + # The other way around, the normal is turned around. + val under := collide(&lying, pose::of(vec3{ 0, 0.9, 0 }), &slab, pose::identity).expect("The box is under the capsule."); + t.expects(under.count == 2 && near(under.normal, vec3{ 0, -1, 0 })); +} + +@test def collides_hulls(t: &mut tester): void { + val slab := shape::box(vec3{ 2, 0.5, 2 }); + val crate := shape::box(vec3{ 0.5, 0.5, 0.5 }); + # A crate resting flat meets the slab at its four corners, midway between + # their surfaces. + val resting := collide(&slab, pose::identity, &crate, pose::of(vec3{ 0, 0.9, 0 })).expect("The crate rests on the slab."); + t.expects(resting.count == 4 && near(resting.normal, vec3{ 0, 1, 0 })); + var corners := true; + for i in 0..4u { + val p := resting.points[i]; + corners = corners && near(p.depth, 0.1) && near(p.point.y, 0.45) && near(math::abs(p.point.x), 0.5) && near(math::abs(p.point.z), 0.5); + } + t.expects(corners); + t.expects(collide(&slab, pose::identity, &crate, pose::of(vec3{ 0, 1.1, 0 })) is none); + t.expects(collide(&slab, pose::identity, &crate, pose::of(vec3{ 0, 1.1, 0 }), 0.2) is some(m) && m.count == 4 && near(m.depth, -0.1)); + val flipped := collide(&crate, pose::of(vec3{ 0, 0.9, 0 }), &slab, pose::identity).expect("The slab is under the crate."); + t.expects(flipped.count == 4 && near(flipped.normal, vec3{ 0, -1, 0 }) && near(flipped.depth, 0.1)); + # Turned about y, still at four. + val turned := collide(&slab, pose::identity, &crate, pose::of(vec3{ 0, 0.9, 0 }, quat::axis_angle(vec3::up, 0.7))).expect("The turned crate rests on the slab."); + t.expects(turned.count == 4 && near(turned.normal, vec3{ 0, 1, 0 }) && near(turned.depth, 0.1)); + + # On its edge, at the edge's two ends; on its corner, at the corner. + val half_diagonal := math::sqrt(0.5f); + val on_edge := collide(&slab, pose::identity, &crate, pose::of(vec3{ 0, 0.4 + half_diagonal, 0 }, quat::axis_angle(vec3::back, math::pi as f32 / 4))).expect("Its edge meets the slab."); + t.expects(on_edge.count == 2 && near(on_edge.normal, vec3{ 0, 1, 0 }) && near(on_edge.points[0].depth, 0.1) && near(on_edge.points[1].depth, 0.1)); + t.expects(near(math::abs(on_edge.points[0].point.z), 0.5) && near(on_edge.points[0].point.x, 0)); + val pointing := quat::axis_angle(vec3::right, math::atan(math::sqrt(0.5f))) * quat::axis_angle(vec3::back, math::pi as f32 / 4); + val half_cube := math::sqrt(0.75f); + val on_corner := collide(&slab, pose::identity, &crate, pose::of(vec3{ 0, 0.4 + half_cube, 0 }, pointing)).expect("Its corner meets the slab."); + t.expects(on_corner.count == 1 && near(on_corner.normal, vec3{ 0, 1, 0 }) && near(on_corner.depth, 0.1) && near(on_corner.points[0].point, vec3{ 0, 0.45, 0 })); + + # Edge across edge, at one point between them, the normal along neither's + # face. + val ridge := pose::of(vec3::zero, quat::axis_angle(vec3::right, math::pi as f32 / 4)); + val keel := pose::of(vec3{ 0, 2 * half_diagonal - 0.1, 0 }, quat::axis_angle(vec3::back, math::pi as f32 / 4)); + val crossed := collide(&crate, ridge, &crate, keel).expect("The edges cross."); + t.expects(crossed.count == 1 && near(crossed.normal, vec3{ 0, 1, 0 }) && near(crossed.depth, 0.1) && near(crossed.points[0].point, vec3{ 0, half_diagonal - 0.05, 0 })); + t.expects(!overlaps(&crate, ridge, &crate, pose::of(vec3{ 0, 2 * half_diagonal + 0.05, 0 }, keel.turn))); + # A hull of places meets as a box does. + val cube := shape::hull_of(corners_of_cube()[:]).expect("A cube is made."); + val stacked := collide(&slab, pose::identity, &cube, pose::of(vec3{ 0, 1.4, 0 })).expect("The cube rests on the slab."); + t.expects(stacked.count == 4 && near(stacked.normal, vec3{ 0, 1, 0 }) && near(stacked.depth, 0.1)); +} + +@test def casts_rays_at_shapes(t: &mut tester): void { + val up := vec3{ 0, 1, 0 }; + val ball := shape::sphere(1); + val struck := ball.ray_cast(pose::of(vec3{ 3, 0, 0 }), vec3::zero, vec3{ 1, 0, 0 }, 10).expect("It meets the ball."); + t.expects(near(struck.distance, 2) && near(struck.point, vec3{ 2, 0, 0 }) && near(struck.normal, vec3{ -1, 0, 0 })); + t.expects(ball.ray_cast(pose::of(vec3{ 3, 0, 0 }), vec3::zero, up, 10) is none); + t.expects(ball.ray_cast(pose::of(vec3{ 3, 0, 0 }), vec3::zero, vec3{ 1, 0, 0 }, 1.5) is none); + val inside := ball.ray_cast(pose::of(vec3{ 3, 0, 0 }), vec3{ 3, 0, 0 }, up, 10).expect("It begins within the ball."); + t.expects(inside.distance == 0 && near(inside.normal, vec3{ 0, -1, 0 })); + + # A box, turned a quarter, its long side up and down. + val box := shape::box(vec3{ 1, 0.5, 0.5 }); + val roof := box.ray_cast(pose::of(vec3{ 0, 5, 0 }, quarter_about(vec3::back)), vec3::zero, up, 10).expect("It meets the box."); + t.expects(near(roof.distance, 4) && near(roof.normal, vec3{ 0, -1, 0 }) && near(roof.point, vec3{ 0, 4, 0 })); + t.expects(box.ray_cast(pose::of(vec3{ 0, 5, 0 }), vec3::zero, up, 4) is none); + t.expects(box.ray_cast(pose::of(vec3{ 0, 5, 0 }), vec3{ 2, 0, 0 }, up, 10) is none); + + # A capsule, by its side, along and across it, and by its round end. + val pill := shape::capsule(vec3{ -1, 3, 0 }, vec3{ 1, 3, 0 }, 0.5); + val side := pill.ray_cast(pose::identity, vec3::zero, up, 10).expect("It meets the capsule's side."); + t.expects(near(side.distance, 2.5) && near(side.normal, vec3{ 0, -1, 0 })); + val across := pill.ray_cast(pose::identity, vec3{ 0.2, 3, -5 }, vec3{ 0, 0, 1 }, 10).expect("It meets the capsule's side."); + t.expects(near(across.distance, 4.5) && near(across.normal, vec3{ 0, 0, -1 })); + val end := pill.ray_cast(pose::identity, vec3{ 3, 3, 0 }, vec3{ -1, 0, 0 }, 10).expect("It meets the capsule's end."); + t.expects(near(end.distance, 1.5) && near(end.normal, vec3{ 1, 0, 0 })); + t.expects(pill.ray_cast(pose::identity, vec3{ 0, 4, 0 }, vec3{ 1, 0, 0 }, 10) is none); +} + +# Numbers from 0 to 1, each of the last, as an LCG makes them. +struct dice { + var state: u64; +} + +def dice::next(&mut this): f32 { + this.state = math::wrapping_add(math::wrapping_mul(this.state, 6364136223846793005), 1442695040888963407); + return (this.state >> 40) as f32 / (1u << 24) as f32; +} + +# A box somewhere within 100 of the origin, as large as 3. +def some_box(seed: &mut dice): bounds { + val at := vec3{ seed.next() * 200 - 100, seed.next() * 200 - 100, seed.next() * 200 - 100 }; + return bounds::around(at, vec3{ 0.1 + seed.next() * 1.4, 0.1 + seed.next() * 1.4, 0.1 + seed.next() * 1.4 }); +} + +# How far along a ray it meets a box, if within reach. +def hit_within(box: bounds, from: vec3, way: vec3, reach: f32): maybe { + val r := ray{ from, way }; + if r.hit(box) is some(at) { + return at if at <= reach; + } + return nothing{}; +} + +@test def sorts_boxes_in_a_tree(t: &mut tester): void { + var seed := dice{ state = 7 }; + var tree := aabb_tree::new(0.25); + var boxes := vector::::new(); + var leaves := vector::::new(); + for i in 0..500u { + val box := some_box(&mut seed); + boxes.append(box); + leaves.append(tree.insert(box, i)); + } + t.expects(tree.length == 500 && tree.is_sound() && tree.height <= 18); + + # Moved a little, a leaf stays; moved further, it's put again. Half are + # removed. + t.expects(!tree.move(leaves[0], bounds{ boxes[0].min + vec3{ 0.1, 0, 0 }, boxes[0].max + vec3{ 0.1, 0, 0 } })); + for i in 0..500u { + if i % 2 == 0 { + boxes[i] = some_box(&mut seed); + _ = tree.move(leaves[i], boxes[i]); + } else if i % 4 == 1 { + tree.remove(leaves[i]); + } + } + t.expects(tree.length == 375 && tree.is_sound()); + + # What a box meets is what a brute search finds, of the leaves' grown boxes. + for k in 0..20u { + val asked := bounds::around(vec3{ seed.next() * 200 - 100, seed.next() * 200 - 100, seed.next() * 200 - 100 }, vec3{ 20, 20, 20 }); + var found := vector::::new(); + tree.query(asked, def(leaf: u32, data: u64): bool { + found.append(data); + return true; + }); + var expected: u64 = 0; + for i in 0..500u { + if i % 4 != 1 && tree.box_of(leaves[i]).overlaps(asked) { + expected++; + } + } + t.expects(found.length == expected); + } + + # The nearest box along a ray, the search narrowing as each is met. + val from := vec3{ -120, 3, -2 }; + val way := vec3{ 1, 0.05, 0.02 }.normalized(); + var nearest: f32 = 1000; + tree.ray_cast(from, way, 1000, def(leaf: u32, data: u64, reach: f32): f32 { + if hit_within(boxes[data], from, way, reach) is some(at) { + nearest = math::min(nearest, at); + return at; + } + return reach; + }); + var expected: f32 = 1000; + for i in 0..500u { + if i % 4 != 1 && hit_within(boxes[i], from, way, 1000) is some(at) { + expected = math::min(expected, at); + } + } + t.expects(near(nearest, expected)); + for i in 0..500u { + if i % 4 != 1 { + tree.remove(leaves[i]); + } + } + t.expects(tree.length == 0 && tree.is_sound() && tree.height == 0); +} + +# A rotation of some axis and angle. +def some_turn(seed: &mut dice): quat { + val axis := vec3{ seed.next() - 0.5, seed.next() - 0.5, seed.next() - 0.5 }; + return quat::axis_angle(axis.length_squared > 1e-4 ? axis : vec3::up, seed.next() * 6.3); +} + +# A hull's corners and face normals, and its edges' directions, in space. +struct placed_hull { + var points: vector; + var normals: vector; + var edges: vector; +} + +def placed_of(h: &hull, at: pose): placed_hull { + var made := placed_hull{ points = vector::::new(), normals = vector::::new(), edges = vector::::new() }; + for i in 0..h.count { + made.points.append(at.apply(h.point(i))); + } + for f in 0..h.faces { + made.normals.append(at.rotate(h.normal(f))); + } + for e in 0..h.edges { + val ends := h.edge(e); + made.edges.append(at.rotate(h.point(ends[1]) - h.point(ends[0]))); + } + return made; +} + +# How far apart two hulls are along an axis, below 0 where they overlap. +def apart_along(a: &placed_hull, b: &placed_hull, axis: vec3): f32 { + var a_low := 1e30f; + var a_high := -1e30f; + var b_low := 1e30f; + var b_high := -1e30f; + for i in 0..a.points.length { + a_low = math::min(a_low, axis.dot(a.points[i])); + a_high = math::max(a_high, axis.dot(a.points[i])); + } + for i in 0..b.points.length { + b_low = math::min(b_low, axis.dot(b.points[i])); + b_high = math::max(b_high, axis.dot(b.points[i])); + } + return math::max(b_low - a_high, a_low - b_high); +} + +# How far apart two hulls are, by every axis that may part them: each face's +# normal, and the cross of every pair of edges, none passed over. +def apart_by_every_axis(a: &placed_hull, b: &placed_hull): f32 { + var most := -1e30f; + for i in 0..a.normals.length { + most = math::max(most, apart_along(a, b, a.normals[i])); + } + for i in 0..b.normals.length { + most = math::max(most, apart_along(a, b, b.normals[i])); + } + for i in 0..a.edges.length { + for j in 0..b.edges.length { + val axis := a.edges[i].cross(b.edges[j]); + continue if axis.length_squared <= 1e-8 * a.edges[i].length_squared * b.edges[j].length_squared; + most = math::max(most, apart_along(a, b, axis.normalized())); + } + } + return most; +} + +# Places within a box of so many each way from the origin. +def some_places(seed: &mut dice, count: u32, reach: f32): vector { + var made := vector::::new(); + for i in 0..count { + made.append(vec3{ (seed.next() * 2 - 1) * reach, (seed.next() * 2 - 1) * reach, (seed.next() * 2 - 1) * reach }); + } + return move(made); +} + +# How far a place is from a box about the origin, turned and placed by a pose: +# below 0, how deep within it. +def from_box(half: vec3, at: pose, p: vec3): f32 { + val local := at.unapply(p); + val out := local.abs() - half; + val outside := out.max(vec3::zero).length; + return outside if outside > 0; + return math::max(out.x, math::max(out.y, out.z)); +} + +@test def agrees_with_a_full_search(t: &mut tester): void { + var seed := dice{ state = 11 }; + # Boxes and hulls of places, turned every way, as near as to meet about + # half the time: met where no axis parts them, as deep as the axis parting + # them least, but where a face is taken over another or an edge as good, + # a few percent deeper. + var tested: u32 = 0; + var met: u32 = 0; + var agreed: u32 = 0; + var deep_enough: u32 = 0; + for i in 0..400u { + var a := shape::box(vec3{ 0.2 + seed.next(), 0.2 + seed.next(), 0.2 + seed.next() }); + var b := shape::box(vec3{ 0.2 + seed.next(), 0.2 + seed.next(), 0.2 + seed.next() }); + if i % 2 == 1 { + a = shape::hull_of(some_places(&mut seed, 12, 1).span).expect("A hull is made."); + b = shape::hull_of(some_places(&mut seed, 12, 1).span).expect("A hull is made."); + } + val at_a := pose::of(vec3::zero, some_turn(&mut seed)); + val at_b := pose::of(vec3{ seed.next() * 3 - 1.5, seed.next() * 3 - 1.5, seed.next() * 3 - 1.5 }, some_turn(&mut seed)); + val apart := apart_by_every_axis(&placed_of(a.as_hull(), at_a), &placed_of(b.as_hull(), at_b)); + continue if math::abs(apart) < 1e-4; + tested++; + val found := collide(&a, at_a, &b, at_b); + if (found is some(_)) == (apart < 0) { + agreed++; + } + if found is some(m) { + met++; + if math::abs(m.depth + apart) <= 2e-3 + 0.075 * math::abs(apart) && m.count >= 1 && near(m.normal.length, 1) { + deep_enough++; + } + } + } + t.expects(tested > 350 && agreed == tested && met > 100 && deep_enough == met); + + # Spheres and capsules against boxes, against their nearest places: a + # capsule's of a thousand along its segment. + var spheres_agreed: u32 = 0; + var capsules_agreed: u32 = 0; + for i in 0..200u { + val half := vec3{ 0.2 + seed.next(), 0.2 + seed.next(), 0.2 + seed.next() }; + val box := shape::box(half); + val at_box := pose::of(vec3::zero, some_turn(&mut seed)); + val r := 0.1 + seed.next() * 0.6; + val center := vec3{ seed.next() * 3 - 1.5, seed.next() * 3 - 1.5, seed.next() * 3 - 1.5 }; + val ball := shape::sphere(r); + val gap := from_box(half, at_box, center) - r; + if math::abs(gap) < 1e-4 { + spheres_agreed++; + } else if collide(&box, at_box, &ball, pose::of(center)) is some(m) { + if gap < 0 && near(m.depth, -gap) && near(m.normal.length, 1) { + spheres_agreed++; + } + } else if gap > 0 { + spheres_agreed++; + } + val pill := shape::pill(r * 2, r * 2 + 0.2 + seed.next()); + val at_pill := pose::of(center, some_turn(&mut seed)); + var nearest := 1e30f; + for k in 0..=1000u { + val along := pill.a.lerp(pill.b, k as f32 / 1000); + nearest = math::min(nearest, from_box(half, at_box, at_pill.apply(along))); + } + # Where its segment passes within the box, only whether they meet. + val pill_gap := nearest - r; + if math::abs(pill_gap) < 2e-3 { + capsules_agreed++; + } else if collide(&box, at_box, &pill, at_pill) is some(m) { + if pill_gap < 0 && (nearest <= 0 || math::abs(m.depth + pill_gap) <= 2e-3) { + capsules_agreed++; + } + } else if pill_gap > 0 { + capsules_agreed++; + } + } + t.expects(spheres_agreed == 200 && capsules_agreed == 200); +} + +# A floor of 8 by 8 squares, each of two triangles, from -4 to 4 along x and +# z, and a wall up its +x side, 2 high, facing in. +def room(): triangle_mesh { + var points := vector::::new(); + var indices := vector::::new(); + for i in 0..9u { + for j in 0..9u { + points.append(vec3{ i as f32 - 4, 0, j as f32 - 4 }); + } + } + for i in 0..8u { + for j in 0..8u { + val p00 := (i * 9 + j) as u32; + val p01 := p00 + 1; + val p10 := p00 + 9; + val p11 := p10 + 1; + for each in [p00, p01, p10, p10, p01, p11] { + indices.append(each); + } + } + } + val w := points.length as u32; + points.append(vec3{ 4, 0, -4 }); + points.append(vec3{ 4, 0, 4 }); + points.append(vec3{ 4, 2, -4 }); + points.append(vec3{ 4, 2, 4 }); + for each in [w, w + 1, w + 2, w + 2, w + 1, w + 3] { + indices.append(each); + } + # A triangle of no area, and one of a place past the rest, left out. + val skipped: u32[6] = [0, 1, 2, 0, 1, 500]; + for i in 0..6u { + indices.append(skipped[i]); + } + return triangle_mesh::new(points.span, indices.span); +} + +# The manifolds a shape meets a mesh with. +def met(m: &triangle_mesh, at: pose, s: &shape, at_s: pose): vector { + var found := vector::::new(); + m.collide(at, s, at_s, 0, def(triangle: u32, each: manifold): bool { + found.append(each); + return true; + }); + return found; +} + +# Whether each manifold pushes along a direction, as deep as `depth`. +def all_along(found: &vector, normal: vec3, depth: f32): bool { + for i in 0..found.length { + return false if !near(found[i].normal, normal) || !near(found[i].depth, depth); + } + return !found.empty; +} + +@test def meets_a_mesh_of_triangles(t: &mut tester): void { + val m := room(); + t.expects(m.length == 130 && near(m.normal(0), vec3{ 0, 1, 0 }) && near(m.normal(128), vec3{ -1, 0, 0 })); + # The floor's edges between its own triangles are flat, so they don't push; + # those along its sides, of one triangle alone, do. + t.expects(!m.is_active(9, 1) && !m.is_active(9, 2) && m.is_active(0, 0) && m.is_active(128, 0)); + + # A crate on the floor, over the corner of four squares: pushed up by each + # triangle it's over. + val crate := shape::box(vec3{ 0.5, 0.5, 0.5 }); + val resting := met(&m, pose::identity, &crate, pose::of(vec3{ 0.1, 0.45, -0.2 })); + t.expects(resting.length >= 4 && all_along(&resting, vec3{ 0, 1, 0 }, 0.05)); + # A ball sunk into it beside a seam: the triangles past the seam meet it by + # their edges, flat, so they push it up as their faces do. + val ball := shape::sphere(0.5); + val sunk := met(&m, pose::identity, &ball, pose::of(vec3{ 0.1, 0.3, 0.35 })); + t.expects(sunk.length >= 3 && all_along(&sunk, vec3{ 0, 1, 0 }, 0.2)); + # Against the wall, pushed back from it alone; in the corner, by both. + t.expects(all_along(&met(&m, pose::identity, &ball, pose::of(vec3{ 3.7, 1, 0 })), vec3{ -1, 0, 0 }, 0.2)); + val cornered := met(&m, pose::identity, &ball, pose::of(vec3{ 3.7, 0.4, 0.5 })); + var up: u64 = 0; + var back: u64 = 0; + for i in 0..cornered.length { + if near(cornered[i].normal, vec3{ 0, 1, 0 }) && near(cornered[i].depth, 0.1) { + up++; + } else if near(cornered[i].normal, vec3{ -1, 0, 0 }) && near(cornered[i].depth, 0.2) { + back++; + } + } + t.expects(up >= 1 && back >= 1 && up + back == cornered.length); + t.expects(m.overlaps(pose::identity, &ball, pose::of(vec3{ 0, 0.4, 0 })) && !m.overlaps(pose::identity, &ball, pose::of(vec3{ 0, 0.6, 0 }))); + # The mesh placed elsewhere is met there. + val moved := pose::of(vec3{ 20, 0, 0 }); + t.expects(met(&m, moved, &ball, pose::of(vec3{ 20, 0.3, 0 })).length >= 1 && met(&m, moved, &ball, pose::of(vec3{ 0, 0.3, 0 })).empty); + + # Rays down to the floor, up at it from below, and into the wall. + val down := m.ray_cast(pose::identity, vec3{ 0.3, 5, 0.2 }, vec3{ 0, -1, 0 }, 10).expect("It meets the floor."); + t.expects(near(down.distance, 5) && near(down.normal, vec3{ 0, 1, 0 }) && near(down.point, vec3{ 0.3, 0, 0.2 })); + val from_below := m.ray_cast(pose::identity, vec3{ 0.3, -1, 0.2 }, vec3{ 0, 1, 0 }, 10).expect("It meets the floor from below."); + t.expects(near(from_below.distance, 1) && near(from_below.normal, vec3{ 0, -1, 0 })); + val wall := m.ray_cast(pose::identity, vec3{ 0, 1, 0 }, vec3{ 1, 0, 0 }, 10).expect("It meets the wall."); + t.expects(near(wall.distance, 4) && near(wall.normal, vec3{ -1, 0, 0 }) && wall.triangle >= 128); + t.expects(m.ray_cast(pose::identity, vec3{ 0, 1, 0 }, vec3{ 1, 0, 0 }, 3) is none); + t.expects(m.ray_cast(moved, vec3{ 20.3, 5, 0.2 }, vec3{ 0, -1, 0 }, 10) is some(h) && near(h.point, vec3{ 20.3, 0, 0.2 })); +} diff --git a/tests/space2d.sakura b/tests/space2d.sakura new file mode 100644 index 0000000..7cd919a --- /dev/null +++ b/tests/space2d.sakura @@ -0,0 +1,359 @@ +#! Contains the tests of `physics2d`'s space: shapes' masses; a box dropped +#! onto the ground, coming to rest on it; a tower of boxes standing still; +#! bodies sleeping and waking; bouncing and sliding by restitution and +#! friction; layers, sensors, and what began and stopped touching; kinematic +#! bodies carrying what rests on them; joints holding bodies; and rays. + +import std::testing; +import std::containers; +import std::math; +import malunal::linear; +import malunal::physics2d; + +def close(a: f32, b: f32, within: f32): bool { + return math::abs(a - b) <= within; +} + +# A space with a ground whose top is at y = 0, wide and flat. +def grounded(s: &mut space): body_id { + val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, -1 }) }); + _ = s.attach(ground, collider{ shape = shape::box(vec2{ 50, 1 }) }); + return ground; +} + +def steps(s: &mut space, seconds: f32): void { + val n := (seconds * 60) as u32; + for i in 0..n { + s.step(1f / 60f); + } +} + +@test def finds_masses(t: &mut tester): void { + val box := shape::box(vec2{ 1, 0.5 }).mass(1); + t.expects(close(box.mass, 2, 1e-5) && close(box.center.length, 0, 1e-5) && close(box.inertia, 2f * 5f / 12f, 1e-5)); + val ball := shape::circle(1, vec2{ 2, 0 }).mass(2); + t.expects(close(ball.mass, 2 * math::pi as f32, 1e-5) && close(ball.center.x, 2, 1e-5) && close(ball.inertia, math::pi as f32, 1e-5)); + # A capsule as thin as a rod: its round ends weigh nearly nothing. + val rod := shape::capsule(vec2{ -1, 0 }, vec2{ 1, 0 }, 0.001).mass(1); + t.expects(close(rod.mass, 0.004, 1e-4) && close(rod.inertia, rod.mass * 4 / 12, 1e-5)); + # A box moved off its body's origin weighs the same, about its own center. + val off := shape::box(vec2{ 1, 0.5 }, vec2{ 3, 1 }).mass(1); + t.expects(close(off.mass, 2, 1e-5) && close(off.center.x, 3, 1e-5) && close(off.center.y, 1, 1e-5) && close(off.inertia, box.inertia, 1e-4)); + # Two shapes together, about their joint center. + val both := box.add(&off); + t.expects(close(both.mass, 4, 1e-5) && close(both.center.x, 1.5, 1e-5) && close(both.inertia, 2 * box.inertia + 4 * (1.5 * 1.5 + 0.25), 1e-3)); +} + +@test def drops_a_box_onto_the_ground(t: &mut tester): void { + var s := space::new(); + _ = grounded(&mut s); + val crate := s.add(body{ at = pose::of(vec2{ 0, 4 }) }); + _ = s.attach(crate, collider{ shape = shape::box(vec2{ 0.5, 0.5 }) }); + t.expects(close(s.mass_of(crate).mass, 1, 1e-5)); + var began: u32 = 0; + for i in 0..120u { + s.step(1f / 60f); + for e in s.events() { + if e.began { + began++; + } + } + } + # It rests on the ground, within the slop contacts allow, and still. + val at := s.pose_of(crate); + t.expects(close(at.at.y, 0.5, 0.01) && close(at.at.x, 0, 1e-3) && close(at.turn.angle, 0, 1e-3)); + t.expects(s.velocity_of(crate).length < 0.01 && began == 1 && s.contact_count == 1); + # Touching the ground still, as the space visits it. + var touching: u32 = 0; + s.each_touching(def(x: collider_id, y: collider_id, sensor: bool): bool { + touching++; + return !sensor; + }); + t.expects(touching == 1); +} + +@test def stands_a_tower_still(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + _ = grounded(&mut s); + var top := body_id{}; + for i in 0..10u { + top = s.add(body{ at = pose::of(vec2{ 0, 0.5 + i as f32 }) }); + _ = s.attach(top, collider{ shape = shape::box(vec2{ 0.5, 0.5 }) }); + } + steps(&mut s, 5); + val at := s.pose_of(top); + t.expects(close(at.at.x, 0, 0.01) && close(at.at.y, 9.5, 0.05) && close(at.turn.angle, 0, 0.01)); + t.expects(s.velocity_of(top).length < 0.01); +} + +@test def sleeps_and_wakes(t: &mut tester): void { + var s := space::new(); + _ = grounded(&mut s); + val lower := s.add(body{ at = pose::of(vec2{ 0, 0.5 }) }); + _ = s.attach(lower, collider{ shape = shape::box(vec2{ 0.5, 0.5 }) }); + val upper := s.add(body{ at = pose::of(vec2{ 0, 1.5 }) }); + _ = s.attach(upper, collider{ shape = shape::box(vec2{ 0.5, 0.5 }) }); + val apart := s.add(body{ at = pose::of(vec2{ 10, 0.5 }) }); + _ = s.attach(apart, collider{ shape = shape::box(vec2{ 0.5, 0.5 }) }); + steps(&mut s, 2); + t.expects(!s.is_awake(lower) && !s.is_awake(upper) && !s.is_awake(apart)); + # A blow wakes what it strikes, and what it rests with, but not what's apart. + s.apply_impulse(upper, vec2{ 0.1, 0 }, s.center_of(upper)); + t.expects(s.is_awake(lower) && s.is_awake(upper) && !s.is_awake(apart)); + steps(&mut s, 2); + t.expects(!s.is_awake(upper)); + # What rested on a body taken away wakes, and falls. + s.remove(lower); + t.expects(s.is_awake(upper) && !s.has(lower)); + steps(&mut s, 1); + t.expects(close(s.pose_of(upper).at.y, 0.5, 0.02)); +} + +@test def pulls_bodies_by_gravities_of_their_own(t: &mut tester): void { + # A space of no gravity, but a world in its middle pulling a rock toward + # its middle wherever the rock is. + var s := space::new(vec2::zero); + val world := s.add(body{ kind = body_kind::static }); + _ = s.attach(world, collider{ shape = shape::circle(10) }); + val rock := s.add(body{ at = pose::of(vec2{ 14, 0 }), gravity = vec2{ -10, 0 } }); + _ = s.attach(rock, collider{ shape = shape::circle(0.5) }); + for i in 0..240u { + s.set_gravity(rock, s.center_of(rock).normalized() * -10); + s.step(1f / 60f); + } + # It fell onto the world's side, and rests there. + t.expects((s.center_of(rock) - vec2{ 10.5, 0 }).length < 0.05 && (s.gravity_of(rock) - vec2{ -10, 0 }).length < 0.01); + steps(&mut s, 2); + t.expects(!s.is_awake(rock)); + # Its pull found again, as it was, leaves it asleep; turned away, it wakes + # it, and the rock falls away. + s.set_gravity(rock, vec2{ -10.001, 0 }); + t.expects(!s.is_awake(rock)); + s.set_gravity(rock, vec2{ 10, 0 }); + steps(&mut s, 1); + t.expects(s.center_of(rock).x > 13); +} + +@test def bounces_and_slides(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + _ = grounded(&mut s); + # A ball of restitution 1 bounces back about as high as it fell. + val ball := s.add(body{ at = pose::of(vec2{ 0, 2.5 }) }); + _ = s.attach(ball, collider{ shape = shape::circle(0.5), restitution = 1 }); + var highest: f32 = 0; + var fell := false; + for i in 0..90u { + s.step(1f / 60f); + val y := s.pose_of(ball).at.y; + if y < 0.6 { + fell = true; + } + if fell { + highest = math::max(highest, y); + } + } + t.expects(fell && close(highest, 2.5, 0.15)); + # On a slope of 30°, a box of friction 1 stays, and of none slides. + var hill := space::new(); + hill.sleeping = false; + val slope := hill.add(body{ kind = body_kind::static, at = pose::of(vec2::zero, math::pi as f32 / 6) }); + _ = hill.attach(slope, collider{ shape = shape::box(vec2{ 20, 0.5 }) }); + val up := rot::of(math::pi as f32 / 6).apply(vec2{ 0, 1 }); + val sticky := hill.add(body{ at = pose::of(up * 1.0, math::pi as f32 / 6) }); + _ = hill.attach(sticky, collider{ shape = shape::box(vec2{ 0.5, 0.5 }), friction = 1 }); + val slick := hill.add(body{ at = pose::of(up * 1.0 + rot::of(math::pi as f32 / 6).apply(vec2{ 5, 0 }), math::pi as f32 / 6) }); + _ = hill.attach(slick, collider{ shape = shape::box(vec2{ 0.5, 0.5 }), friction = 0 }); + steps(&mut hill, 1); + t.expects(hill.velocity_of(sticky).length < 0.05 && close(hill.velocity_of(slick).length, 5, 0.25)); +} + +@test def meets_by_layers_and_sensors(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + _ = grounded(&mut s); + # On a layer the ground's mask doesn't hold, it falls through. + val ghost := s.add(body{ at = pose::of(vec2{ -5, 1 }) }); + _ = s.attach(ghost, collider{ shape = shape::box(vec2{ 0.5, 0.5 }), layers = 2, mask = 2 }); + # A sensor notes what falls through it. + val zone := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 5, 4 }) }); + val field := s.attach(zone, collider{ shape = shape::box(vec2{ 1, 1 }), sensor = true }); + val stone := s.add(body{ at = pose::of(vec2{ 5, 7 }) }); + val heavy := s.attach(stone, collider{ shape = shape::circle(0.25) }); + var entered := false; + var left := false; + for i in 0..120u { + s.step(1f / 60f); + for e in s.events() { + if e.sensor && ((e.a == field && e.b == heavy) || (e.a == heavy && e.b == field)) { + entered = entered || e.began; + left = left || !e.began; + } + } + } + t.expects(s.pose_of(ghost).at.y < -5 && entered && left && close(s.pose_of(stone).at.y, 0.25, 0.01)); +} + +@test def senses_what_moves_and_filters_queries(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + # A sensor standing still notes a kinematic body moving through it, as a coin + # notes a character walking, but never what stands still beside it. + val coin := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, 0 }) }); + val field := s.attach(coin, collider{ shape = shape::circle(0.5), sensor = true, data = 7 }); + val post := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0.5, 0 }) }); + val pole := s.attach(post, collider{ shape = shape::box(vec2{ 0.25, 0.25 }), data = 8 }); + val walker := s.add(body{ kind = body_kind::kinematic, at = pose::of(vec2{ -3, 0 }), velocity = vec2{ 3, 0 } }); + val feet := s.attach(walker, collider{ shape = shape::circle(0.25), data = 9 }); + var walked_in := false; + var walked_out := false; + var post_met := false; + for i in 0..120u { + s.step(1f / 60f); + for e in s.events() { + val of_field := e.a == field || e.b == field; + if of_field && (e.a == feet || e.b == feet) { + walked_in = walked_in || e.began; + walked_out = walked_out || !e.began; + } + post_met = post_met || (of_field && (e.a == pole || e.b == pole)); + } + } + t.expects(walked_in && walked_out && !post_met); + + # Queries pass over sensors unless asked of them, and the asker's own. + val probe := shape::circle(0.1); + var met: u32 = 0; + s.overlap(&probe, pose::identity, 0xFFFFFFFF, def(c: collider_id, b: body_id): bool { met++; return true; }); + t.expects(met == 0); + s.overlap(&probe, pose::identity, query_filter{ sensors = true }, def(c: collider_id, b: body_id): bool { met++; return true; }); + t.expects(met == 1); + t.expects(s.ray_cast(vec2{ -2, 0 }, vec2{ 1, 0 }, 10) is some(&hit) && hit.collider == pole); + t.expects(s.ray_cast(vec2{ -2, 0 }, vec2{ 1, 0 }, 10, query_filter{ sensors = true }) is some(&hit) && hit.collider == field); + t.expects(s.ray_cast(vec2{ -2, 0 }, vec2{ 1, 0 }, 10, query_filter{ ignore = 8 }) is some(&hit) && hit.collider == feet); +} + +@test def carries_what_rests_on_a_kinematic_body(t: &mut tester): void { + var s := space::new(); + _ = grounded(&mut s); + val lift := s.add(body{ kind = body_kind::kinematic, at = pose::of(vec2{ 0, 2 }) }); + _ = s.attach(lift, collider{ shape = shape::box(vec2{ 2, 0.25 }) }); + val crate := s.add(body{ at = pose::of(vec2{ 0, 2.75 }) }); + _ = s.attach(crate, collider{ shape = shape::box(vec2{ 0.5, 0.5 }) }); + steps(&mut s, 1); + s.set_velocity(lift, vec2{ 1, 0 }); + steps(&mut s, 1); + # The lift moves as set, and carries the crate, by friction, along. + t.expects(close(s.pose_of(lift).at.x, 1, 0.02) && close(s.pose_of(lift).at.y, 2, 1e-4)); + t.expects(close(s.pose_of(crate).at.x, 1, 0.1) && close(s.velocity_of(crate).x, 1, 0.1)); +} + +@test def holds_bodies_by_joints(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + val ground := grounded(&mut s); + # A pendulum swings about its pin, its bob kept as far from it. + val bob := s.add(body{ at = pose::of(vec2{ 3, 5 }) }); + _ = s.attach(bob, collider{ shape = shape::circle(0.25) }); + val pin := s.pin(ground, bob, vec2{ 0, 5 }); + var farthest: f32 = 0; + var nearest: f32 = 10; + for i in 0..120u { + s.step(1f / 60f); + val reach := (s.pose_of(bob).at - vec2{ 0, 5 }).length; + farthest = math::max(farthest, reach); + nearest = math::min(nearest, reach); + } + t.expects(close(farthest, 3, 0.02) && close(nearest, 3, 0.02) && s.has(pin)); + # A wheel on an axle, turned by a motor at its speed. + val wheel := s.add(body{ at = pose::of(vec2{ 10, 3 }), gravity_scale = 0 }); + _ = s.attach(wheel, collider{ shape = shape::circle(0.5) }); + val axle := s.pin(ground, wheel, vec2{ 10, 3 }); + var turning := s.joint_of(axle); + turning.motor = true; + turning.motor_speed = 2; + turning.max_motor_force = 100; + s.change(axle, turning); + steps(&mut s, 1); + t.expects(close(s.spin_of(wheel), 2, 0.01) && close(s.pose_of(wheel).at.x, 10, 1e-3)); + # A door limited to a quarter turn. + val door := s.add(body{ at = pose::of(vec2{ 21, 4 }) }); + _ = s.attach(door, collider{ shape = shape::box(vec2{ 1, 0.1 }) }); + val hinge := s.pin(ground, door, vec2{ 20, 4 }); + var limited := s.joint_of(hinge); + limited.limit = true; + limited.lower = -math::pi as f32 / 4; + limited.upper = 0; + s.change(hinge, limited); + steps(&mut s, 2); + t.expects(close(s.angle_of(hinge), -math::pi as f32 / 4, 0.02)); + # A rod keeps two bodies apart; a weld keeps them as one. + val left := s.add(body{ at = pose::of(vec2{ -10, 6 }) }); + _ = s.attach(left, collider{ shape = shape::circle(0.25) }); + val right := s.add(body{ at = pose::of(vec2{ -8, 6 }) }); + _ = s.attach(right, collider{ shape = shape::circle(0.25) }); + _ = s.tie(left, right, vec2{ -10, 6 }, vec2{ -8, 6 }); + val stuck := s.add(body{ at = pose::of(vec2{ -10, 7 }) }); + _ = s.attach(stuck, collider{ shape = shape::box(vec2{ 0.25, 0.25 }) }); + _ = s.weld(left, stuck, vec2{ -10, 6.5 }); + steps(&mut s, 2); + t.expects(close((s.pose_of(right).at - s.pose_of(left).at).length, 2, 0.02)); + val held := s.pose_of(left).unapply(s.pose_of(stuck).at); + t.expects(close(held.x, 0, 0.02) && close(held.y, 1, 0.02) && close(unturned(s.pose_of(stuck).turn.angle - s.pose_of(left).turn.angle), 0, 0.02)); +} + +def unturned(angle: f32): f32 { + val pi := math::pi as f32; + return angle < -pi ? angle + 2 * pi : angle > pi ? angle - 2 * pi : angle; +} + +@test def slides_across_a_grid_without_catching(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + # A floor of 40 cells and a wall, its top at y = 0. + var cells := grid::new(40, 4); + val wide: u32 = 40; + val high: u32 = 4; + for x in 0..wide { + cells.set(x, 0, true); + } + for y in 0..high { + cells.set(39, y, true); + } + val floor := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ -20, -1 }) }); + val ground := s.attach_grid(floor, move(cells), collider{ friction = 0 }); + val crate := s.add(body{ at = pose::of(vec2{ -18, 0.5 }), velocity = vec2{ 4, 0 } }); + _ = s.attach(crate, collider{ shape = shape::box(vec2{ 0.5, 0.5 }), friction = 0 }); + var lowest: f32 = 1; + var slowest: f32 = 4; + for i in 0..180u { + s.step(1f / 60f); + lowest = math::min(lowest, s.pose_of(crate).at.y); + slowest = math::min(slowest, s.velocity_of(crate).x); + } + # Across 12 seams it neither sank, bounced, nor slowed, nor turned. + t.expects(close(s.pose_of(crate).at.x, -6, 0.1) && close(lowest, 0.5, 0.01) && close(slowest, 4, 0.05) && close(s.spin_of(crate), 0, 0.01)); + # Then it meets the wall and stops at it, within a few centimeters, and as + # it slides freely, pushed back out of the wall no faster than a little. + var farthest: f32 = 0; + for i in 0..420u { + s.step(1f / 60f); + farthest = math::max(farthest, s.pose_of(crate).at.x); + } + t.expects(close(farthest, 18.5, 0.05) && math::abs(s.velocity_of(crate).x) < 0.25); + val hit := s.ray_cast(vec2{ 5, 3 }, vec2{ 0, -1 }, 10).expect("It meets the floor."); + t.expects(hit.collider == ground && close(hit.distance, 3, 1e-4)); +} + +@test def casts_rays_in_space(t: &mut tester): void { + var s := space::new(); + val ground := grounded(&mut s); + val crate := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 3, 0.5 }) }); + val side := s.attach(crate, collider{ shape = shape::box(vec2{ 0.5, 0.5 }), layers = 2 }); + val hit := s.ray_cast(vec2{ 0, 0.5 }, vec2{ 1, 0 }, 10).expect("It meets the crate."); + t.expects(hit.collider == side && hit.body == crate && close(hit.distance, 2.5, 1e-4) && close(hit.normal.x, -1, 1e-4)); + val down := s.ray_cast(vec2{ 3, 5 }, vec2{ 0, -1 }, 10, 1).expect("It passes the crate to the ground."); + t.expects(down.body == ground && close(down.distance, 5, 1e-4)); + t.expects(s.ray_cast(vec2{ 0, 5 }, vec2{ 0, 1 }, 10) is none); +} diff --git a/tests/space3d.sakura b/tests/space3d.sakura new file mode 100644 index 0000000..82df38f --- /dev/null +++ b/tests/space3d.sakura @@ -0,0 +1,365 @@ +#! Contains the tests of `physics3d`'s space: shapes' masses and inertia; a +#! box dropped onto the ground, coming to rest on it; a tower of boxes standing +#! still; bodies sleeping and waking; bouncing and sliding by restitution and +#! friction; layers, sensors, and what began and stopped touching; kinematic +#! bodies carrying what rests on them; joints holding bodies; a mesh's floor +#! slid across without catching at its seams; and rays. + +import std::testing; +import std::containers; +import std::math; +import malunal::linear; +import malunal::physics3d; + +def close(a: f32, b: f32, within: f32): bool { + return math::abs(a - b) <= within; +} + +def close(a: vec3, b: vec3, within: f32): bool { + return (a - b).length <= within; +} + +# A space with a ground whose top is at y = 0, wide and flat. +def grounded(s: &mut space): body_id { + val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ 0, -1, 0 }) }); + _ = s.attach(ground, collider{ shape = shape::box(vec3{ 50, 1, 50 }) }); + return ground; +} + +def steps(s: &mut space, seconds: f32): void { + val n := (seconds * 60) as u32; + for i in 0..n { + s.step(1f / 60f); + } +} + +def cube(s: &mut space, at: vec3, half: f32): body_id { + val made := s.add(body{ at = pose::of(at) }); + _ = s.attach(made, collider{ shape = shape::box(vec3{ half, half, half }) }); + return made; +} + +@test def finds_masses_and_inertia(t: &mut tester): void { + # A box of 2 by 1 by 1: its tensor about each axis m(b² + c²)/12. + val box := shape::box(vec3{ 1, 0.5, 0.5 }).mass(1); + t.expects(close(box.mass, 2, 1e-4) && close(box.center, vec3::zero, 1e-5)); + t.expects(close(box.inertia.x_axis.x, 2f * 2f / 12f, 1e-4) && close(box.inertia.y_axis.y, 2f * 5f / 12f, 1e-4) && close(box.inertia.z_axis.z, 2f * 5f / 12f, 1e-4)); + t.expects(close(box.inertia.x_axis.y, 0, 1e-5) && close(box.inertia.x_axis.z, 0, 1e-5)); + # A ball: 2mr²/5 about every axis. + val ball := shape::sphere(1, vec3{ 0, 2, 0 }).mass(1); + val m := 4f / 3f * math::pi as f32; + t.expects(close(ball.mass, m, 1e-4) && close(ball.center.y, 2, 1e-5) && close(ball.inertia.y_axis.y, 0.4 * m, 1e-4)); + # A hull of a box's corners weighs as the box does. + var corners := vector::::new(); + for k in 0..8u { + corners.append(vec3{ (k & 1) != 0 ? 1f : -1f, (k & 2) != 0 ? 0.5f : -0.5f, (k & 4) != 0 ? 0.5f : -0.5f }); + } + val hulled := shape::hull_of(corners.span).expect("A box's hull is made.").mass(1); + t.expects(close(hulled.mass, 2, 1e-4) && close(hulled.inertia.x_axis.x, box.inertia.x_axis.x, 1e-4) && close(hulled.inertia.y_axis.y, box.inertia.y_axis.y, 1e-4)); + # A capsule along x: about its own axis as a cylinder and a ball, the least. + val pill := shape::capsule(vec3{ -1, 0, 0 }, vec3{ 1, 0, 0 }, 0.5).mass(1); + t.expects(close(pill.mass, math::pi as f32 * 0.25 * 2 + 4f / 3f * math::pi as f32 * 0.125, 1e-4)); + t.expects(pill.inertia.x_axis.x < pill.inertia.y_axis.y && close(pill.inertia.y_axis.y, pill.inertia.z_axis.z, 1e-4)); + # Two together, about their joint center. + val both := box.add(&shape::box(vec3{ 1, 0.5, 0.5 }, vec3{ 0, 3, 0 }).mass(1)); + t.expects(close(both.mass, 4, 1e-4) && close(both.center.y, 1.5, 1e-4) && close(both.inertia.x_axis.x, 2 * box.inertia.x_axis.x + 4 * 1.5 * 1.5, 1e-3)); +} + +@test def drops_a_box_onto_the_ground(t: &mut tester): void { + var s := space::new(); + _ = grounded(&mut s); + val crate := cube(&mut s, vec3{ 0, 4, 0 }, 0.5); + t.expects(close(s.mass_of(crate).mass, 1, 1e-4)); + var began: u32 = 0; + for i in 0..120u { + s.step(1f / 60f); + for e in s.events() { + if e.began { + began++; + } + } + } + val at := s.pose_of(crate); + t.expects(close(at.at, vec3{ 0, 0.5, 0 }, 0.01) && close(at.turn.dot(quat::identity), 1, 1e-4)); + t.expects(s.velocity_of(crate).length < 0.01 && began == 1 && s.contact_count == 1); + # Touching the ground still, as the space visits it. + var touching: u32 = 0; + s.each_touching(def(x: collider_id, y: collider_id, sensor: bool): bool { + touching++; + return !sensor; + }); + t.expects(touching == 1); +} + +@test def stands_a_tower_still(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + _ = grounded(&mut s); + var top := body_id{}; + for i in 0..8u { + top = cube(&mut s, vec3{ 0, 0.5 + i as f32, 0 }, 0.5); + } + steps(&mut s, 4); + t.expects(close(s.pose_of(top).at, vec3{ 0, 7.5, 0 }, 0.05) && s.velocity_of(top).length < 0.01); +} + +@test def sleeps_and_wakes(t: &mut tester): void { + var s := space::new(); + _ = grounded(&mut s); + val lower := cube(&mut s, vec3{ 0, 0.5, 0 }, 0.5); + val upper := cube(&mut s, vec3{ 0, 1.5, 0 }, 0.5); + val apart := cube(&mut s, vec3{ 10, 0.5, 0 }, 0.5); + steps(&mut s, 2); + t.expects(!s.is_awake(lower) && !s.is_awake(upper) && !s.is_awake(apart)); + s.apply_impulse(upper, vec3{ 0.1, 0, 0 }, s.center_of(upper)); + t.expects(s.is_awake(lower) && s.is_awake(upper) && !s.is_awake(apart)); + steps(&mut s, 2); + t.expects(!s.is_awake(upper)); + s.remove(lower); + t.expects(s.is_awake(upper) && !s.has(lower)); + steps(&mut s, 1); + t.expects(close(s.pose_of(upper).at.y, 0.5, 0.02)); +} + +@test def pulls_bodies_by_gravities_of_their_own(t: &mut tester): void { + # A space of no gravity, but a world in its middle pulling a rock toward + # its middle wherever the rock is. + var s := space::new(vec3::zero); + val world := s.add(body{ kind = body_kind::static }); + _ = s.attach(world, collider{ shape = shape::sphere(10) }); + val rock := s.add(body{ at = pose::of(vec3{ 0, 0, 14 }), gravity = vec3{ 0, 0, -10 } }); + _ = s.attach(rock, collider{ shape = shape::sphere(0.5) }); + for i in 0..240u { + s.set_gravity(rock, s.center_of(rock).normalized() * -10); + s.step(1f / 60f); + } + # It fell onto the world's side, and rests there. + t.expects(close(s.center_of(rock), vec3{ 0, 0, 10.5 }, 0.05) && close(s.gravity_of(rock), vec3{ 0, 0, -10 }, 0.01)); + steps(&mut s, 2); + t.expects(!s.is_awake(rock)); + # Its pull found again, as it was, leaves it asleep; turned away, it wakes + # it, and the rock falls away. + s.set_gravity(rock, vec3{ 0, 0, -10.001 }); + t.expects(!s.is_awake(rock)); + s.set_gravity(rock, vec3{ 0, 0, 10 }); + steps(&mut s, 1); + t.expects(s.center_of(rock).z > 13); +} + +@test def bounces_and_slides(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + _ = grounded(&mut s); + val ball := s.add(body{ at = pose::of(vec3{ 0, 2.5, 0 }) }); + _ = s.attach(ball, collider{ shape = shape::sphere(0.5), restitution = 1 }); + var highest: f32 = 0; + var fell := false; + for i in 0..90u { + s.step(1f / 60f); + val y := s.pose_of(ball).at.y; + if y < 0.6 { + fell = true; + } + if fell { + highest = math::max(highest, y); + } + } + t.expects(fell && close(highest, 2.5, 0.15)); + # On a slope of 30°, a box of friction 1 stays, and of none slides. + var hill := space::new(); + hill.sleeping = false; + val tilt := quat::axis_angle(vec3::back, math::pi as f32 / 6); + val slope := hill.add(body{ kind = body_kind::static, at = pose::of(vec3::zero, tilt) }); + _ = hill.attach(slope, collider{ shape = shape::box(vec3{ 20, 0.5, 20 }) }); + val up := tilt * vec3::up; + val sticky := hill.add(body{ at = pose::of(up, tilt) }); + _ = hill.attach(sticky, collider{ shape = shape::box(vec3{ 0.5, 0.5, 0.5 }), friction = 1 }); + val slick := hill.add(body{ at = pose::of(up + vec3{ 0, 0, 5 }, tilt) }); + _ = hill.attach(slick, collider{ shape = shape::box(vec3{ 0.5, 0.5, 0.5 }), friction = 0 }); + steps(&mut hill, 1); + t.expects(hill.velocity_of(sticky).length < 0.05 && close(hill.velocity_of(slick).length, 5, 0.25)); +} + +@test def meets_by_layers_and_sensors(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + _ = grounded(&mut s); + val ghost := s.add(body{ at = pose::of(vec3{ -5, 1, 0 }) }); + _ = s.attach(ghost, collider{ shape = shape::box(vec3{ 0.5, 0.5, 0.5 }), layers = 2, mask = 2 }); + val zone := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ 5, 4, 0 }) }); + val field := s.attach(zone, collider{ shape = shape::box(vec3{ 1, 1, 1 }), sensor = true }); + val stone := s.add(body{ at = pose::of(vec3{ 5, 7, 0 }) }); + val heavy := s.attach(stone, collider{ shape = shape::sphere(0.25) }); + var entered := false; + var left := false; + for i in 0..120u { + s.step(1f / 60f); + for e in s.events() { + if e.sensor && ((e.a == field && e.b == heavy) || (e.a == heavy && e.b == field)) { + entered = entered || e.began; + left = left || !e.began; + } + } + } + t.expects(s.pose_of(ghost).at.y < -5 && entered && left && close(s.pose_of(stone).at.y, 0.25, 0.01)); +} + +@test def senses_what_moves_and_filters_queries(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + # A sensor standing still notes a kinematic body moving through it, as a gem + # notes a character walking, but never what stands still beside it. + val gem := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ 0, 0, 0 }) }); + val field := s.attach(gem, collider{ shape = shape::sphere(0.5), sensor = true, data = 7 }); + val post := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ 0.5, 0, 0 }) }); + val pole := s.attach(post, collider{ shape = shape::box(vec3{ 0.25, 0.25, 0.25 }), data = 8 }); + val walker := s.add(body{ kind = body_kind::kinematic, at = pose::of(vec3{ -3, 0, 0 }), velocity = vec3{ 3, 0, 0 } }); + val feet := s.attach(walker, collider{ shape = shape::sphere(0.25), data = 9 }); + var walked_in := false; + var walked_out := false; + var post_met := false; + for i in 0..120u { + s.step(1f / 60f); + for e in s.events() { + val of_field := e.a == field || e.b == field; + if of_field && (e.a == feet || e.b == feet) { + walked_in = walked_in || e.began; + walked_out = walked_out || !e.began; + } + post_met = post_met || (of_field && (e.a == pole || e.b == pole)); + } + } + t.expects(walked_in && walked_out && !post_met); + + # Queries pass over sensors unless asked of them, and the asker's own. + val probe := shape::sphere(0.1); + var met: u32 = 0; + s.overlap(&probe, pose::identity, 0xFFFFFFFF, def(c: collider_id, b: body_id): bool { met++; return true; }); + t.expects(met == 0); + s.overlap(&probe, pose::identity, query_filter{ sensors = true }, def(c: collider_id, b: body_id): bool { met++; return true; }); + t.expects(met == 1); + t.expects(s.ray_cast(vec3{ -2, 0, 0 }, vec3{ 1, 0, 0 }, 10) is some(&hit) && hit.collider == pole); + t.expects(s.ray_cast(vec3{ -2, 0, 0 }, vec3{ 1, 0, 0 }, 10, query_filter{ sensors = true }) is some(&hit) && hit.collider == field); + t.expects(s.ray_cast(vec3{ -2, 0, 0 }, vec3{ 1, 0, 0 }, 10, query_filter{ ignore = 8 }) is some(&hit) && hit.collider == feet); +} + +@test def carries_what_rests_on_a_kinematic_body(t: &mut tester): void { + var s := space::new(); + _ = grounded(&mut s); + val lift := s.add(body{ kind = body_kind::kinematic, at = pose::of(vec3{ 0, 2, 0 }) }); + _ = s.attach(lift, collider{ shape = shape::box(vec3{ 2, 0.25, 2 }) }); + val crate := cube(&mut s, vec3{ 0, 2.75, 0 }, 0.5); + steps(&mut s, 1); + s.set_velocity(lift, vec3{ 1, 0, 0 }); + steps(&mut s, 1); + t.expects(close(s.pose_of(lift).at, vec3{ 1, 2, 0 }, 0.02)); + t.expects(close(s.pose_of(crate).at.x, 1, 0.1) && close(s.velocity_of(crate).x, 1, 0.1)); +} + +@test def holds_bodies_by_joints(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + val ground := grounded(&mut s); + # A pendulum on a ball joint keeps its bob as far from it. + val bob := s.add(body{ at = pose::of(vec3{ 3, 5, 0 }) }); + _ = s.attach(bob, collider{ shape = shape::sphere(0.25) }); + _ = s.ball(ground, bob, vec3{ 0, 5, 0 }); + var farthest: f32 = 0; + var nearest: f32 = 10; + for i in 0..120u { + s.step(1f / 60f); + val reach := (s.pose_of(bob).at - vec3{ 0, 5, 0 }).length; + farthest = math::max(farthest, reach); + nearest = math::min(nearest, reach); + } + t.expects(close(farthest, 3, 0.03) && close(nearest, 3, 0.03)); + # A wheel on a hinge, turned by a motor at its speed about its axle alone. + val wheel := s.add(body{ at = pose::of(vec3{ 10, 3, 0 }), gravity_scale = 0, angular_damping = 0 }); + _ = s.attach(wheel, collider{ shape = shape::sphere(0.5) }); + val axle := s.hinge(ground, wheel, vec3{ 10, 3, 0 }, vec3::back); + var turning := s.joint_of(axle); + turning.motor = true; + turning.motor_speed = 2; + turning.max_motor_force = 100; + s.change(axle, turning); + steps(&mut s, 1); + t.expects(close(s.spin_of(wheel), vec3{ 0, 0, 2 }, 0.02) && close(s.pose_of(wheel).at, vec3{ 10, 3, 0 }, 1e-3)); + # A door, hinged up its side, limited to a quarter turn, swung by a push. + val door := s.add(body{ at = pose::of(vec3{ 21, 4, 0 }), gravity_scale = 0 }); + _ = s.attach(door, collider{ shape = shape::box(vec3{ 1, 1, 0.1 }) }); + val hinge := s.hinge(ground, door, vec3{ 20, 4, 0 }, vec3::up); + var limited := s.joint_of(hinge); + limited.limit = true; + limited.lower = -math::pi as f32 / 4; + limited.upper = math::pi as f32 / 4; + s.change(hinge, limited); + s.apply_impulse(door, vec3{ 0, 0, -3 }, vec3{ 22, 4, 0 }); + steps(&mut s, 2); + t.expects(close(s.angle_of(hinge), math::pi as f32 / 4, 0.03) && close(s.pose_of(door).turn.y * s.pose_of(door).turn.y + s.pose_of(door).turn.w * s.pose_of(door).turn.w, 1, 1e-3)); + # A rod keeps two bodies apart; a fixed joint keeps them as one. + val left := s.add(body{ at = pose::of(vec3{ -10, 6, 0 }) }); + _ = s.attach(left, collider{ shape = shape::sphere(0.25) }); + val right := s.add(body{ at = pose::of(vec3{ -8, 6, 0 }) }); + _ = s.attach(right, collider{ shape = shape::sphere(0.25) }); + _ = s.tie(left, right, vec3{ -10, 6, 0 }, vec3{ -8, 6, 0 }); + val stuck := cube(&mut s, vec3{ -10, 7, 0 }, 0.25); + _ = s.fix(left, stuck, vec3{ -10, 6.5, 0 }); + steps(&mut s, 2); + t.expects(close((s.pose_of(right).at - s.pose_of(left).at).length, 2, 0.02)); + val held := s.pose_of(left).unapply(s.pose_of(stuck).at); + t.expects(close(held, vec3{ 0, 1, 0 }, 0.03) && close(math::abs(s.pose_of(left).turn.dot(s.pose_of(stuck).turn)), 1, 1e-3)); +} + +@test def slides_across_a_mesh_without_catching(t: &mut tester): void { + var s := space::new(); + s.sleeping = false; + # A floor of 20 by 20 squares, two triangles each, its top at y = 0. + var points := vector::::new(); + var indices := vector::::new(); + val n: u32 = 20; + for z in 0..n + 1 { + for x in 0..n + 1 { + points.append(vec3{ x as f32 - 10, 0, z as f32 - 10 }); + } + } + for z in 0..n { + for x in 0..n { + val at := z * (n + 1) + x; + indices.append(at); + indices.append(at + n + 1); + indices.append(at + 1); + indices.append(at + 1); + indices.append(at + n + 1); + indices.append(at + n + 2); + } + } + val floor := s.add(body{ kind = body_kind::static }); + val ground := s.attach_mesh(floor, triangle_mesh::new(points.span, indices.span), collider{ friction = 0 }); + val crate := s.add(body{ at = pose::of(vec3{ -8, 0.5, 0.3 }), velocity = vec3{ 4, 0, 0 } }); + _ = s.attach(crate, collider{ shape = shape::box(vec3{ 0.5, 0.5, 0.5 }), friction = 0 }); + var lowest: f32 = 1; + var slowest: f32 = 4; + for i in 0..180u { + s.step(1f / 60f); + lowest = math::min(lowest, s.pose_of(crate).at.y); + slowest = math::min(slowest, s.velocity_of(crate).x); + } + # Across 12 seams it neither sank, bounced, nor slowed. + t.expects(close(s.pose_of(crate).at.x, 4, 0.1) && close(lowest, 0.5, 0.01) && close(slowest, 4, 0.05)); + t.expects(close(s.pose_of(crate).at.y, 0.5, 0.01) && math::abs(s.spin_of(crate).length) < 0.01); + # A ray meets the mesh's triangle under it. + val hit := s.ray_cast(vec3{ 2.5, 5, 2.5 }, vec3::down, 10, 0xFFFFFFFF).expect("It meets the floor."); + t.expects(hit.collider == ground && close(hit.distance, 5, 1e-4) && hit.triangle != 0xFFFFFFFF); +} + +@test def casts_rays_in_space(t: &mut tester): void { + var s := space::new(); + val ground := grounded(&mut s); + val crate := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ 3, 0.5, 0 }) }); + val side := s.attach(crate, collider{ shape = shape::box(vec3{ 0.5, 0.5, 0.5 }), layers = 2 }); + val hit := s.ray_cast(vec3{ 0, 0.5, 0 }, vec3::right, 10).expect("It meets the crate."); + t.expects(hit.collider == side && hit.body == crate && close(hit.distance, 2.5, 1e-4) && close(hit.normal, vec3::left, 1e-4)); + val down := s.ray_cast(vec3{ 3, 5, 0 }, vec3::down, 10, 1).expect("It passes the crate to the ground."); + t.expects(down.body == ground && close(down.distance, 5, 1e-4)); + t.expects(s.ray_cast(vec3{ 0, 5, 0 }, vec3::up, 10) is none); +} diff --git a/tools/bench.sakura b/tools/bench.sakura new file mode 100644 index 0000000..561dc92 --- /dev/null +++ b/tools/bench.sakura @@ -0,0 +1,304 @@ +#! Times what `linear` does most, each over a thousand values two thousand +#! times, against the same worked a number at a time on a `vec3` of 12 bytes, +#! as hearth's scenes worked it before: adding and scaling vectors, their dots +#! and lengths, quaternions' products and turns, and matrices' products, +#! points, and inverses. +#! +#! Each pass is a function of its own, as a system is, and what it times is +#! called from elsewhere too, so nothing is inlined only for being called once: +#! the code an executable makes of a loop hangs on what is around it. +#! +#! `blossom build`, then run `malunal.linear.bench`, as an executable +#! optimized with `-O2`: the VM works numbers one at a time either way. + +import std::io; +import std::math; +import std::time; +import std::containers; +import malunal::linear; + +# A vector of three of 12 bytes, and the rest, as they were before. +struct old3 { var x: f32; var y: f32; var z: f32; } +struct oldq { var x: f32; var y: f32; var z: f32; var w: f32; } +struct oldm { var m: f32[16]; } + +def old3::add(&this, o: &old3): old3 { return old3{ this.x + o.x, this.y + o.y, this.z + o.z }; } +def old3::mul(&this, by: &f32): old3 { return old3{ this.x * by, this.y * by, this.z * by }; } +def old3::dot(&this, o: old3): f32 { return this.x * o.x + this.y * o.y + this.z * o.z; } +def old3::cross(&this, o: old3): old3 { return old3{ this.y * o.z - this.z * o.y, this.z * o.x - this.x * o.z, this.x * o.y - this.y * o.x }; } +def old3::normalized(&this): old3 { + val l := math::sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + return l > 0 ? old3{ this.x / l, this.y / l, this.z / l } : old3{}; +} + +def oldq::mul(&this, o: &oldq): oldq { + return oldq{ + this.w * o.x + this.x * o.w + this.y * o.z - this.z * o.y, + this.w * o.y - this.x * o.z + this.y * o.w + this.z * o.x, + this.w * o.z + this.x * o.y - this.y * o.x + this.z * o.w, + this.w * o.w - this.x * o.x - this.y * o.y - this.z * o.z, + }; +} + +def oldq::turn(&this, v: &old3): old3 { + val q := old3{ this.x, this.y, this.z }; + val t := q.cross(v) * 2; + return v + t * this.w + q.cross(t); +} + +def oldm::mul(&this, other: &oldm): oldm { + var made := oldm{}; + for c in 0..4u { + for r in 0..4u { + made.m[c * 4 + r] = this.m[r] * other.m[c * 4] + this.m[4 + r] * other.m[c * 4 + 1] + + this.m[8 + r] * other.m[c * 4 + 2] + this.m[12 + r] * other.m[c * 4 + 3]; + } + } + return made; +} + +# A matrix of three as one would be worked a number at a time. +struct old33 { var x: old3; var y: old3; var z: old3; } + +def old33::turned(&this, v: &old3): old3 { + return old3{ + this.x.x * v.x + this.y.x * v.y + this.z.x * v.z, + this.x.y * v.x + this.y.y * v.y + this.z.y * v.z, + this.x.z * v.x + this.y.z * v.y + this.z.z * v.z, + }; +} + +def old33::mul(&this, o: &old33): old33 { + return old33{ this.turned(&o.x), this.turned(&o.y), this.turned(&o.z) }; +} + +def oldm::point(&this, p: old3): old3 { + return old3{ + this.m[0] * p.x + this.m[4] * p.y + this.m[8] * p.z + this.m[12], + this.m[1] * p.x + this.m[5] * p.y + this.m[9] * p.z + this.m[13], + this.m[2] * p.x + this.m[6] * p.y + this.m[10] * p.z + this.m[14], + }; +} + +const count: u64 = 1024; +const rounds: u64 = 2000; +const dt: f32 = 0.016; + +# What each pass works over. +struct data { + var ps: vector; + var vs: vector; + var qs: vector; + var ms: vector; + var rs: vector; + var ws: vector; + var out: vector; + var ops: vector; + var ovs: vector; + var oqs: vector; + var oms: vector; + var oout: vector; + var ors: vector; + var r_out: vector; + var or_out: vector; + var sum: f32; +} + +# How long a pass took, for each value, beside what it took before. +def report(what: strview, started: &instant, before: f64): f64 { + val ns := started.elapsed().in_nanoseconds as f64 / (count * rounds) as f64; + if before == 0 { + println($"{what}: {ns} ns"); + } else { + println($"{what}: {ns} ns, before {before} ns, {before / ns}x"); + } + return ns; +} + +def step_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ops[i] = d.ops[i] + d.ovs[i] * dt; } } + return report("vec3 p + v * dt, before", &at, 0); +} +def step(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ps[i] = d.ps[i] + d.vs[i] * dt; } } + _ = report("vec3 p + v * dt", &at, before); +} + +def dots_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.ops[i].dot(d.ovs[i]); } } + return report("vec3 dot, before", &at, 0); +} +def dots(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.ps[i].dot(d.vs[i]); } } + _ = report("vec3 dot", &at, before); +} + +def normals_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ovs[i] = (d.ovs[i] + d.ops[i]).normalized(); } } + return report("vec3 normalized, before", &at, 0); +} +def normals(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.vs[i] = (d.vs[i] + d.ps[i]).normalized(); } } + _ = report("vec3 normalized", &at, before); +} + +def crosses_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ovs[i] = d.ovs[i].cross(d.ops[i]); } } + return report("vec3 cross, before", &at, 0); +} +def crosses(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.vs[i] = d.vs[i].cross(d.ps[i]); } } + _ = report("vec3 cross", &at, before); +} + +def turns_before(d: &mut data, by: &oldq): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.oqs[i] = d.oqs[i] * by; } } + return report("quat * quat, before", &at, 0); +} +def turns(d: &mut data, by: &quat, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.qs[i] = d.qs[i] * by; } } + _ = report("quat * quat", &at, before); +} + +def rotations_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ops[i] = d.oqs[i].turn(&d.ops[i]); } } + return report("quat * vec3, before", &at, 0); +} +def rotations(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ps[i] = d.qs[i] * d.ps[i]; } } + _ = report("quat * vec3", &at, before); +} + +def directions(d: &mut data): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ps[i] = d.rs[i] * d.ps[i]; } } + _ = report("mat3 * vec3", &at, 0); +} + +def tensors_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.or_out[i] = d.ors[i] * d.ors[(i + 1) % count]; } } + return report("mat3 * mat3, a number at a time", &at, 0); +} +def tensors(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.r_out[i] = d.rs[i] * d.rs[(i + 1) % count]; } } + _ = report("mat3 * mat3", &at, before); +} + +def products_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.oout[i] = d.oms[i] * d.oms[(i + 1) % count]; } } + return report("mat4 * mat4, before", &at, 0); +} +def products(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.out[i] = d.ms[i] * d.ms[(i + 1) % count]; } } + _ = report("mat4 * mat4", &at, before); +} + +def projections(d: &mut data): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ws[i] = d.ms[i] * d.ws[i]; } } + _ = report("mat4 * vec4", &at, 0); +} + +def points_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ops[i] = d.oms[i].point(d.ops[i]); } } + return report("mat4 transform_point, before", &at, 0); +} +def points(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.ps[i] = d.ms[i].transform_point(d.ps[i]); } } + _ = report("mat4 transform_point", &at, before); +} + +def inverses(d: &mut data): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.out[i] = d.ms[i].inverse(); } } + _ = report("mat4 inverse", &at, 0); +} + +# Each of what's timed, called once more, so none is called from one place. +def elsewhere(d: &mut data): void { + d.ps[0] = d.ps[1] + d.vs[1] * 2; + d.ops[0] = d.ops[1] + d.ovs[1] * 2; + d.sum += d.ps[1].dot(d.vs[1]) + d.ops[1].dot(d.ovs[1]); + d.vs[0] = d.vs[1].normalized().cross(d.ps[1]); + d.ovs[0] = d.ovs[1].normalized().cross(d.ops[1]); + d.qs[0] = d.qs[1] * d.qs[2]; + d.oqs[0] = d.oqs[1] * d.oqs[2]; + d.ps[0] = d.qs[1] * (d.rs[1] * d.ps[1]); + d.ops[0] = d.oqs[1].turn(&d.ops[1]); + d.out[0] = d.ms[1] * d.ms[2]; + d.oout[0] = d.oms[1] * d.oms[2]; + d.r_out[0] = d.rs[1] * d.rs[2]; + d.or_out[0] = d.ors[1] * d.ors[2]; + d.ws[0] = d.ms[1] * d.ws[1]; + d.ps[0] = d.ms[1].transform_point(d.ps[1]); + d.ops[0] = d.oms[1].point(d.ops[1]); + d.out[0] = d.ms[1].inverse(); +} + +def main(): void { + println($"lanes held: {lanes_held()}"); + var d := data{ + ps = vector::::new(), vs = vector::::new(), qs = vector::::new(), ms = vector::::new(), + rs = vector::::new(), ws = vector::::new(), out = vector::::new(), ops = vector::::new(), + ovs = vector::::new(), oqs = vector::::new(), oms = vector::::new(), oout = vector::::new(), + ors = vector::::new(), r_out = vector::::new(), or_out = vector::::new(), + }; + for i in 0..count { + d.ps.append(vec3{ i as f32 * 0.001, 1, 2 }); + d.vs.append(vec3{ 0.5, 0.25, 0.125 }); + d.ops.append(old3{ i as f32 * 0.001, 1, 2 }); + d.ovs.append(old3{ 0.5, 0.25, 0.125 }); + val q := quat::axis_angle(vec3{ 1, 2, i as f32 }, i as f32 * 0.01); + d.qs.append(q); + d.oqs.append(oldq{ q.x, q.y, q.z, q.w }); + val r := mat3::rotation(q); + d.rs.append(r); + d.ors.append(old33{ + old3{ r.x_axis.x, r.x_axis.y, r.x_axis.z }, old3{ r.y_axis.x, r.y_axis.y, r.y_axis.z }, old3{ r.z_axis.x, r.z_axis.y, r.z_axis.z }, + }); + val m := mat4::compose(vec3{ i as f32, 1, 2 }, q, vec3{ 1, 2, 1 }); + d.ms.append(m); + d.oms.append(oldm{ m = m.m }); + d.ws.append(vec4{ i as f32, 1, 2, 1 }); + } + d.out.resize(count); + d.oout.resize(count); + d.r_out.resize(count); + d.or_out.resize(count); + elsewhere(&mut d); + + step(&mut d, step_before(&mut d)); + dots(&mut d, dots_before(&mut d)); + normals(&mut d, normals_before(&mut d)); + crosses(&mut d, crosses_before(&mut d)); + val turn := quat::axis_angle(vec3::up, 0.001); + turns(&mut d, &turn, turns_before(&mut d, &oldq{ turn.x, turn.y, turn.z, turn.w })); + rotations(&mut d, rotations_before(&mut d)); + directions(&mut d); + tensors(&mut d, tensors_before(&mut d)); + products(&mut d, products_before(&mut d)); + projections(&mut d); + points(&mut d, points_before(&mut d)); + inverses(&mut d); + + # What was worked, so none of it is left out. + println($"checks: {d.sum} {d.ps[3].y} {d.ops[3].y} {d.vs[5].x} {d.ovs[5].x} {d.qs[7].w} {d.oqs[7].w} {d.out[9].m[5]} {d.oout[9].m[5]} {d.ws[2].y}"); +} diff --git a/tools/geometry_bench.sakura b/tools/geometry_bench.sakura new file mode 100644 index 0000000..0996862 --- /dev/null +++ b/tools/geometry_bench.sakura @@ -0,0 +1,236 @@ +#! Times what `geometry` does most, each over a thousand values two thousand +#! times, against the same worked a number at a time on a `vec3` of 12 bytes: +#! a camera's frustum culling boxes and spheres, rays meeting boxes and +#! spheres, and boxes moved by matrices. +#! +#! Each pass is a function of its own, as a system is, and what it times is +#! called from elsewhere too, so nothing is inlined only for being called once: +#! the code an executable makes of a loop hangs on what is around it. +#! +#! `blossom build`, then run `malunal.geometry.bench`, as an executable +#! optimized with `-O2`: the VM works numbers one at a time either way. + +import std::io; +import std::math; +import std::time; +import std::containers; +import malunal::linear; +import malunal::geometry; + +# The shapes as they'd be written a number at a time, of vectors of 12 bytes. +struct old3 { var x: f32; var y: f32; var z: f32; } +struct oldp { var x: f32; var y: f32; var z: f32; var d: f32; } +struct oldb { var min: old3; var max: old3; } +struct olds { var center: old3; var radius: f32; } +struct oldr { var origin: old3; var direction: old3; } +struct oldm { var m: f32[16]; } + +# Whether a box is in front of each of six planes, of the corner furthest in +# front of each, a plane at a time. +def oldb::seen(&this, planes: &oldp[6]): bool { + for i in 0..6u { + val p := planes[i]; + val x := p.x < 0 ? this.min.x : this.max.x; + val y := p.y < 0 ? this.min.y : this.max.y; + val z := p.z < 0 ? this.min.z : this.max.z; + return false if p.x * x + p.y * y + p.z * z - p.d < 0; + } + return true; +} + +def olds::seen(&this, planes: &oldp[6]): bool { + for i in 0..6u { + val p := planes[i]; + return false if p.x * this.center.x + p.y * this.center.y + p.z * this.center.z - p.d + this.radius < 0; + } + return true; +} + +# Where a ray meets a box, or -1, between the box's faces along each axis. +def oldr::hit(&this, b: &oldb): f32 { + val ix := 1 / this.direction.x; + val iy := 1 / this.direction.y; + val iz := 1 / this.direction.z; + val x0 := (b.min.x - this.origin.x) * ix; + val x1 := (b.max.x - this.origin.x) * ix; + val y0 := (b.min.y - this.origin.y) * iy; + val y1 := (b.max.y - this.origin.y) * iy; + val z0 := (b.min.z - this.origin.z) * iz; + val z1 := (b.max.z - this.origin.z) * iz; + val enter := math::max(math::max(math::min(x0, x1), math::min(y0, y1)), math::max(math::min(z0, z1), 0)); + val leave := math::min(math::min(math::max(x0, x1), math::max(y0, y1)), math::max(z0, z1)); + return enter <= leave ? enter : -1; +} + +# Where a ray meets a sphere, or -1. +def oldr::hit(&this, s: &olds): f32 { + val mx := this.origin.x - s.center.x; + val my := this.origin.y - s.center.y; + val mz := this.origin.z - s.center.z; + val c := mx * mx + my * my + mz * mz - s.radius * s.radius; + return 0 if c <= 0; + val b := mx * this.direction.x + my * this.direction.y + mz * this.direction.z; + return -1 if b >= 0; + val a := this.direction.x * this.direction.x + this.direction.y * this.direction.y + this.direction.z * this.direction.z; + val d := b * b - a * c; + return d < 0 ? -1 : (-b - math::sqrt(d)) / a; +} + +# The box holding a box a matrix moves. +def oldb::moved(&this, by: &oldm): oldb { + val m := &by.m; + val cx := (this.min.x + this.max.x) * 0.5; + val cy := (this.min.y + this.max.y) * 0.5; + val cz := (this.min.z + this.max.z) * 0.5; + val hx := (this.max.x - this.min.x) * 0.5; + val hy := (this.max.y - this.min.y) * 0.5; + val hz := (this.max.z - this.min.z) * 0.5; + val x := m[0] * cx + m[4] * cy + m[8] * cz + m[12]; + val y := m[1] * cx + m[5] * cy + m[9] * cz + m[13]; + val z := m[2] * cx + m[6] * cy + m[10] * cz + m[14]; + val rx := math::abs(m[0]) * hx + math::abs(m[4]) * hy + math::abs(m[8]) * hz; + val ry := math::abs(m[1]) * hx + math::abs(m[5]) * hy + math::abs(m[9]) * hz; + val rz := math::abs(m[2]) * hx + math::abs(m[6]) * hy + math::abs(m[10]) * hz; + return oldb{ old3{ x - rx, y - ry, z - rz }, old3{ x + rx, y + ry, z + rz } }; +} + +const count: u64 = 1024; +const rounds: u64 = 2000; + +# What each pass works over. +struct data { + var boxes: vector; + var spheres: vector; + var rays: vector; + var ms: vector; + var moved: vector; + var oboxes: vector; + var ospheres: vector; + var orays: vector; + var oms: vector; + var omoved: vector; + var seen: u64; + var sum: f32; +} + +# How long a pass took, for each value, beside what it took before. +def report(what: strview, started: &instant, before: f64): f64 { + val ns := started.elapsed().in_nanoseconds as f64 / (count * rounds) as f64; + if before == 0 { + println($"{what}: {ns} ns"); + } else { + println($"{what}: {ns} ns, before {before} ns, {before / ns}x"); + } + return ns; +} + +def culled_boxes_before(d: &mut data, planes: &oldp[6]): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.seen += d.oboxes[i].seen(planes) ? 1 : 0; } } + return report("frustum overlaps bounds, before", &at, 0); +} +def culled_boxes(d: &mut data, f: &frustum, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.seen += f.overlaps(d.boxes[i]) ? 1 : 0; } } + _ = report("frustum overlaps bounds", &at, before); +} + +def culled_spheres_before(d: &mut data, planes: &oldp[6]): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.seen += d.ospheres[i].seen(planes) ? 1 : 0; } } + return report("frustum overlaps sphere, before", &at, 0); +} +def culled_spheres(d: &mut data, f: &frustum, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.seen += f.overlaps(d.spheres[i]) ? 1 : 0; } } + _ = report("frustum overlaps sphere", &at, before); +} + +def boxes_hit_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.orays[i].hit(&d.oboxes[(i + 1) % count]); } } + return report("ray hit bounds, before", &at, 0); +} +def boxes_hit(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.rays[i].hit(d.boxes[(i + 1) % count]) is some(t) ? t : -1; } } + _ = report("ray hit bounds", &at, before); +} + +def spheres_hit_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.orays[i].hit(&d.ospheres[(i + 1) % count]); } } + return report("ray hit sphere, before", &at, 0); +} +def spheres_hit(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.sum += d.rays[i].hit(d.spheres[(i + 1) % count]) is some(t) ? t : -1; } } + _ = report("ray hit sphere", &at, before); +} + +def moves_before(d: &mut data): f64 { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.omoved[i] = d.oboxes[i].moved(&d.oms[i]); } } + return report("bounds transformed, before", &at, 0); +} +def moves(d: &mut data, before: f64): void { + val at := instant::now(); + for _ in 0..rounds { for i in 0..count { d.moved[i] = d.boxes[i].transformed(d.ms[i]); } } + _ = report("bounds transformed", &at, before); +} + +# Each of what's timed, called once more, so none is called from one place. +def elsewhere(d: &mut data, f: &frustum, planes: &oldp[6]): void { + d.seen += (f.overlaps(d.boxes[1]) ? 1 : 0) + (d.oboxes[1].seen(planes) ? 1 : 0); + d.seen += (f.overlaps(d.spheres[1]) ? 1 : 0) + (d.ospheres[1].seen(planes) ? 1 : 0); + d.sum += d.orays[1].hit(&d.oboxes[2]) + d.orays[1].hit(&d.ospheres[2]); + d.sum += (d.rays[1].hit(d.boxes[2]) is some(t) ? t : -1) + (d.rays[1].hit(d.spheres[2]) is some(u) ? u : -1); + d.moved[0] = d.boxes[1].transformed(d.ms[1]); + d.omoved[0] = d.oboxes[1].moved(&d.oms[1]); +} + +def old3_of(v: vec3): old3 { + return old3{ v.x, v.y, v.z }; +} + +def main(): void { + println($"lanes held: {lanes_held()}"); + var d := data{ + boxes = vector::::new(), spheres = vector::::new(), rays = vector::::new(), ms = vector::::new(), + moved = vector::::new(), oboxes = vector::::new(), ospheres = vector::::new(), + orays = vector::::new(), oms = vector::::new(), omoved = vector::::new(), + }; + # A camera at the middle of a field of boxes, seeing about half of them. + val f := frustum::of(mat4::perspective(math::pi as f32 / 3, 16.0 / 9.0, 0.1, 400) * mat4::look_at(vec3{ 0, 5, 0 }, vec3{ 0, 0, -10 })); + var planes: oldp[6]; + for i in 0..6u { + val p := f.planes[i]; + planes[i] = oldp{ p.normal.x, p.normal.y, p.normal.z, p.distance }; + } + for i in 0..count { + val at := vec3{ (i % 32) as f32 * 8 - 128, (i % 3) as f32, (i / 32) as f32 * 8 - 128 }; + val b := bounds::around(at, vec3{ 1, 2, 1.5 }); + d.boxes.append(b); + d.oboxes.append(oldb{ old3_of(b.min), old3_of(b.max) }); + d.spheres.append(sphere{ at, 2 }); + d.ospheres.append(olds{ old3_of(at), 2 }); + val r := ray::toward(vec3{ 0, 5, 0 }, at); + d.rays.append(r); + d.orays.append(oldr{ old3_of(r.origin), old3_of(r.direction) }); + val m := mat4::compose(at, quat::axis_angle(vec3{ 1, 2, i as f32 }, i as f32 * 0.01), vec3{ 1, 2, 1 }); + d.ms.append(m); + d.oms.append(oldm{ m = m.m }); + } + d.moved.resize(count); + d.omoved.resize(count); + elsewhere(&mut d, &f, &planes); + + culled_boxes(&mut d, &f, culled_boxes_before(&mut d, &planes)); + culled_spheres(&mut d, &f, culled_spheres_before(&mut d, &planes)); + boxes_hit(&mut d, boxes_hit_before(&mut d)); + spheres_hit(&mut d, spheres_hit_before(&mut d)); + moves(&mut d, moves_before(&mut d)); + + # What was worked, so none of it is left out. + println($"checks: {d.seen} {d.sum} {d.moved[3].max.y} {d.omoved[3].max.y}"); +} diff --git a/tools/physics2d_bench.sakura b/tools/physics2d_bench.sakura new file mode 100644 index 0000000..f905033 --- /dev/null +++ b/tools/physics2d_bench.sakura @@ -0,0 +1,106 @@ +#! Times `malunal::physics2d`'s space stepping two of Box2D's benchmark scenes, +#! built as Box2D's benchmark builds them, so the times are comparable: a +#! pyramid of 5050 boxes, 100 at its base, stepped 500 times, and 400 pyramids +#! of 55 boxes on 20 floors, stepped 200 times, each at 60 steps a second of 4 +#! substeps, with sleeping off. Each prints how long it took, and where its top +#! box ended, how far it settled, which a stable stack keeps to millimeters. +#! +#! `blossom build`, then run `malunal.physics2d.bench`. + +import std::io; +import std::math; +import std::time; +import std::containers; +import malunal::linear; +import malunal::physics2d; + +def large_pyramid(s: &mut space): body_id { + val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, -1 }) }); + _ = s.attach(ground, collider{ shape = shape::box(vec2{ 100, 1 }) }); + val base: u32 = 100; + val a: f32 = 0.5; + var top := body_id{}; + for i in 0..base { + val y := (2 * i as f32 + 1) * a; + for j in i..base { + val x := (i as f32 + 1) * a + 2 * (j - i) as f32 * a - a * base as f32; + top = s.add(body{ at = pose::of(vec2{ x, y }) }); + _ = s.attach(top, collider{ shape = shape::box(vec2{ a, a }) }); + } + } + return top; +} + +def small_pyramid(s: &mut space, base: u32, extent: f32, center_x: f32, base_y: f32): body_id { + var top := body_id{}; + for i in 0..base { + val y := (2 * i as f32 + 1) * extent + base_y; + for j in i..base { + val x := (i as f32 + 1) * extent + 2 * (j - i) as f32 * extent + center_x - 0.5; + top = s.add(body{ at = pose::of(vec2{ x, y }) }); + _ = s.attach(top, collider{ shape = shape::box(vec2{ extent, extent }) }); + } + } + return top; +} + +def many_pyramids(s: &mut space): body_id { + val base: u32 = 10; + val extent: f32 = 0.5; + val rows: u32 = 20; + val columns: u32 = 20; + val ground := s.add(body{ kind = body_kind::static }); + val ground_step := 2 * extent * (base as f32 + 1); + val width := 2 * extent * columns as f32 * (base as f32 + 1); + var y: f32 = 0; + for i in 0..rows { + _ = s.attach(ground, collider{ shape = shape::segment(vec2{ -0.5 * width, y }, vec2{ 0.5 * width, y }) }); + y += ground_step; + } + val base_width := 2 * extent * base as f32; + var base_y: f32 = 0; + var top := body_id{}; + for i in 0..rows { + for j in 0..columns { + val center_x := -0.5 * width + j as f32 * (base_width + 2 * extent) + 2 * extent; + top = small_pyramid(s, base, extent, center_x, base_y); + } + base_y += ground_step; + } + return top; +} + +def run(name: strview, s: &mut space, top: body_id, steps: u32): void { + val from := s.pose_of(top).at; + val at := instant::now(); + var parts := step_profile{}; + for i in 0..steps { + + s.step(1f / 60f); + parts.pairs += s.profile.pairs; + parts.contacts += s.profile.contacts; + parts.solve += s.profile.solve; + } + val ms := at.elapsed().in_nanoseconds as f64 / 1e6; + val to := s.pose_of(top).at; + println($"{name}: {ms} ms, {ms / steps as f64} ms a step; {s.body_count} bodies, {s.contact_count} contacts; top from ({from.x}, {from.y}) to ({to.x}, {to.y}), turned {s.pose_of(top).turn.angle}"); + println($" finding pairs {parts.pairs / steps as f64} ms, contacts {parts.contacts / steps as f64} ms, solving {parts.solve / steps as f64} ms a step"); +} + +def main(): void { + # On one thread, then on eight. + for round in 0..2u { + val threads: u32 = round == 0 ? 1 : 8; + println($"on {threads} threads:"); + var large := space::new(); + large.sleeping = false; + large.threads = threads; + val large_top := large_pyramid(&mut large); + run("large_pyramid", &mut large, large_top, 500); + var many := space::new(); + many.sleeping = false; + many.threads = threads; + val many_top := many_pyramids(&mut many); + run("many_pyramids", &mut many, many_top, 200); + } +} diff --git a/tools/physics3d_bench.sakura b/tools/physics3d_bench.sakura new file mode 100644 index 0000000..d2aa2ea --- /dev/null +++ b/tools/physics3d_bench.sakura @@ -0,0 +1,120 @@ +#! Times `malunal::physics3d`'s space stepping two of Jolt's performance test +#! scenes, built as Jolt's builds them, so the times are comparable: a pyramid +#! of 1240 boxes, 15 tiers high, none sleeping, and 1764 boxes, spheres, +#! capsules, and pyramids dropped onto a terrain of 20000 triangles, bouncing +#! and coming to rest, each stepped 500 times at 60 steps a second. The +#! pyramid prints where its top box ended: settled on the tiers below, its +#! middle 29 above the floor. +#! +#! `blossom build`, then run `malunal.physics3d.bench`. + +import std::io; +import std::math; +import std::time; +import std::containers; +import malunal::linear; +import malunal::physics3d; + +def pyramid(s: &mut space): body_id { + val floor := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ 0, -1, 0 }) }); + _ = s.attach(floor, collider{ shape = shape::box(vec3{ 50, 1, 50 }) }); + val height: i32 = 15; + var top := body_id{}; + for i in 0..height { + val shift: f32 = (i & 1) != 0 ? 1f : 0f; + var j := i / 2; + while j < height - (i + 1) / 2 { + var k := i / 2; + while k < height - (i + 1) / 2 { + val at := vec3{ (-height + 2 * j) as f32 + shift, 1 + 2.5 * i as f32, (-height + 2 * k) as f32 + shift }; + top = s.add(body{ at = pose::of(at), can_sleep = false }); + _ = s.attach(top, collider{ shape = shape::box(vec3{ 1, 1, 1 }) }); + k++; + } + j++; + } + } + return top; +} + +def terrain(s: &mut space): void { + val n: u32 = 100; + val cell: f32 = 3; + val tallest: f32 = 5; + var points := vector::::new(); + points.resize(((n + 1) * (n + 1)) as u64, vec3::zero); + for x in 0..n + 1 { + for z in 0..n + 1 { + val height := math::sin(x as f32 * 50 / n as f32) * math::cos(z as f32 * 50 / n as f32); + points[(z * (n + 1) + x) as u64] = vec3{ cell * x as f32, tallest * height, cell * z as f32 }; + } + } + var indices := vector::::new(); + for x in 0..n { + for z in 0..n { + val start := (n + 1) * z + x; + indices.append(start); + indices.append(start + n + 1); + indices.append(start + 1); + indices.append(start + 1); + indices.append(start + n + 1); + indices.append(start + n + 2); + } + } + val center := n as f32 * cell / 2; + val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec3{ -center, tallest, -center }) }); + _ = s.attach_mesh(ground, triangle_mesh::new(points.span, indices.span), collider{ friction = 0.5, restitution = 0.6 }); + var tip: vec3[5] = [vec3{ 0, 1, 0 }, vec3{ 1, 0, 0 }, vec3{ -1, 0, 0 }, vec3{ 0, 0, 1 }, vec3{ 0, 0, -1 }]; + var shapes: shape[4] = [ + shape::box(vec3{ 0.5, 0.75, 1 }), shape::sphere(0.5), shape::capsule(vec3{ 0, -0.75, 0 }, vec3{ 0, 0.75, 0 }, 0.5), + shape::hull_of(tip[:]).expect("A pyramid is made."), + ]; + var x: i32 = -10; + while x <= 10 { + for y in 0..4u { + var z: i32 = -10; + while z <= 10 { + val b := s.add(body{ at = pose::of(vec3{ 7.5 * x as f32, 15 + 2 * y as f32, 7.5 * z as f32 }) }); + _ = s.attach(b, collider{ shape = shapes[y], friction = 0.5, restitution = 0.6 }); + z++; + } + } + x++; + } +} + +def run(name: strview, s: &mut space, steps: u32): void { + val at := instant::now(); + var parts := step_profile{}; + var awake_at_end: u64 = 0; + for i in 0..steps { + s.step(1f / 60f); + parts.pairs += s.profile.pairs; + parts.contacts += s.profile.contacts; + parts.solve += s.profile.solve; + parts.sleep += s.profile.sleep; + } + val ms := at.elapsed().in_nanoseconds as f64 / 1e6; + println($"{name}: {ms} ms, {ms / steps as f64} ms a step, {1000 * steps as f64 / ms} steps a second; {s.body_count} bodies, {s.contact_count} contacts"); + println($" finding pairs {parts.pairs / steps as f64} ms, contacts {parts.contacts / steps as f64} ms, solving {parts.solve / steps as f64} ms, sleeping {parts.sleep / steps as f64} ms a step"); +} + +def main(): void { + # On one thread, then on eight. + for round in 0..2u { + val threads: u32 = round == 0 ? 1 : 8; + println($"on {threads} threads:"); + var stacked := space::new(); + stacked.sleeping = false; + stacked.threads = threads; + val top := pyramid(&mut stacked); + val from := stacked.pose_of(top).at; + run("pyramid", &mut stacked, 500); + val to := stacked.pose_of(top).at; + println($" top from ({from.x}, {from.y}, {from.z}) to ({to.x}, {to.y}, {to.z})"); + var dropped := space::new(); + dropped.threads = threads; + terrain(&mut dropped); + run("convex_vs_mesh", &mut dropped, 500); + } +}