Tie two objects with a hinge, a spring, a rope or for good (#154)
Two bodies could not be connected: no door on a hinge, no lamp on
a rope, no wheel on an axle. This is the first step of the issue,
the four joints without a motor. The slider and the motors follow
in a second step under the same issue.
- Joint is a new asset type, placed as a child of the object it
holds, like a collider or a rigidbody. "Add joint…" in the
object menu makes one or places one the project has. An object
takes as many as it needs.
- Where the joint sits is the point it holds its object at. A
hinge and a fixed joint have that one point only. A spring and a
rope end at a connected anchor on the other object, counted in
that object's own units, or in the scene's without one.
- The rows follow the type: length, stiffness and damping for a
spring, length for a rope, an angle limit for a hinge. Length 0
takes the distance the two ends were placed at. The limit counts
from how the two were placed.
- The connected object is an object reference in the schema of the
type. Pasting, containers and removing treat it as they treat
every reference since #258.
- shownFor is a new schema option: a row is shown while an enum of
the same bag holds one of the named values.
- The object needs a rigidbody, its own or one further up. Without
one the joint holds nothing and the console says so once.
- A connected object without a rigidbody is a moving anchor: the
joint has a kinematic body of its own that follows it.
- A connected object destroyed while playing makes the joint let go
with a hint. Removed in the editor the reference empties, so the
joint holds on to the scene. The issue asked for "inactive" there.
- "Add joint" ties two objects while the game runs, from a joint
asset as the template. Destroy on the joint lets go, there is no
Break joint node. Destroy with keep children takes the joints
along with the object.
- The scene view draws a line from each joint to what it holds on
to and rings the held point. A selected spring or rope has a
round handle on its far end, and dragging it is one undo step.
- Joints hold in Play only. The editor run simulates nothing
(#148), and the inspector of a placed joint says so.
- Rapier counts a revolute joint's limits absolutely, not from the
start, so the placed angle is added. Measured with a probe.
- The + menu has 25 types now and no longer fits under its button
on a canvas 800 high. It scrolls there, and e2e 04 scrolls to
the last entry instead of expecting it in view.
Tests:
- Gate on melektaus-atx for this state: 218 files, 3390 tests
(3336 + 54), exit 0.
- e2e 1-16,24,39-46,51,52,57,58 on melektaus-atx: 831 checks, all
pass. Module 41 alone: 25 checks (21 + 4).
- 54 new unit tests: 40 in joints.test.ts (rope, spring, pendulum,
limit, fixed, the other end, the node, containers, paste), 6 for
the line the scene view draws, 4 catalog cases of the node. The
remaining 4 come from tests that make a case per asset type.
- Four new e2e checks in module 41: Add joint from the menu, the
rope to the hook with its line and handle, dragging the handle
with one undo, the bob hanging in Play next to one that falls.
- e2e 04, 40 and 46 count the new type in their lists.
- 21 of 22 unit counter-probes fail their tests. The other one is
equivalent: Rapier ignores removing a joint that left with its
body, the guard stays.
- Three browser counter-probes fail their checks (2, 1 and 2).
- One screenshot looked at: icon, line, handle and the rope rows.
- The e2e sum of 1691 is counted (1687 + 4, 1687 measured by CI
on e066613). The full suite and the smokes did not run.
- Not seen in the browser: spring, hinge with limit and fixed
joint, the node Add joint, a connected object that moves, joints
inside a container, the released game. Unit tests cover them
but the last. Limits under a mirrored parent are not handled.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e066613583
commit
7dd3ae1131
42 files changed
+1917
-27
No files matched your search
@@ -615,8 +615,8 @@ export class World {
|
||||
|
||||
/**
|
||||
* Removes only the entity: its children move up to its parent (top level when it had none) and
|
||||
* stay where they are in the world. Its behaviors and its rigidbody are part of it rather than
|
||||
* things it carries, so they go with it – moved up they would drive the parent instead.
|
||||
* stay where they are in the world. Its behaviors, its rigidbody and its joints are part of it rather
|
||||
* than things it carries, so they go with it – moved up they would drive the parent instead.
|
||||
* Answers the children that moved up.
|
||||
*/
|
||||
removeKeepingChildren(entity: Entity): Entity[] {
|
||||
@@ -624,7 +624,7 @@ export class World {
|
||||
const own = localMatrixOf(entity, transformOf(entity.props));
|
||||
const kept: Entity[] = [];
|
||||
for (const child of this.childrenOf(entity)) {
|
||||
if (child.type === 'behavior' || child.type === 'rigidbody') continue;
|
||||
if (child.type === 'behavior' || child.type === 'rigidbody' || child.type === 'joint') continue;
|
||||
const at = apply(own, child);
|
||||
child.x = at.x;
|
||||
child.y = at.y;
|
||||
|
||||
@@ -63,6 +63,7 @@ import {
|
||||
samePose,
|
||||
} from './bodyGeometry';
|
||||
import { type Rapier, toMetres, toPixels } from './engine';
|
||||
import { type JointHost, JointSet, type RigidOwner } from './joints';
|
||||
import { passesOneWay, reachOf } from './oneWay';
|
||||
|
||||
/** The engine always steps this long, whatever the frame took. */
|
||||
@@ -159,7 +160,15 @@ export class PhysicsSystem implements System, CollisionSource {
|
||||
/** How bodies moved in the world before (#165), until the body of each is made here. */
|
||||
private resumed = new Map<Entity, BodyMotion>();
|
||||
|
||||
constructor(private readonly rapier: Rapier) {}
|
||||
private readonly joints: JointSet;
|
||||
private readonly jointHost: JointHost = {
|
||||
rigidAbove: (from) => this.rigidAbove(from),
|
||||
hint: (world, target, text) => this.hint(world, target, text),
|
||||
};
|
||||
|
||||
constructor(private readonly rapier: Rapier) {
|
||||
this.joints = new JointSet(rapier);
|
||||
}
|
||||
|
||||
start(world: World): void {
|
||||
const engine = new this.rapier.World(this.gravity(world));
|
||||
@@ -176,6 +185,7 @@ export class PhysicsSystem implements System, CollisionSource {
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.joints.clear();
|
||||
this.engine?.free();
|
||||
this.queue?.free();
|
||||
this.engine = null;
|
||||
@@ -421,6 +431,21 @@ export class PhysicsSystem implements System, CollisionSource {
|
||||
}
|
||||
// Only the body an object arrives with moves on: one it gets later starts at rest like any other.
|
||||
this.resumed.clear();
|
||||
this.joints.sync(world, this.engine!, this.jointHost);
|
||||
}
|
||||
|
||||
/** The nearest object from `from` upwards whose body the engine moves by a rigidbody of its own. */
|
||||
private rigidAbove(from: Entity | null): RigidOwner | null {
|
||||
for (let entity = from; entity; entity = entity.parent) {
|
||||
const body = this.bodies.get(entity);
|
||||
if (body?.kind === 'rigid') return { entity, body: body.body };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether a joint holds its two ends right now (#154): it does not without a rigidbody to hold. */
|
||||
holdsJoint(joint: Entity): boolean {
|
||||
return this.joints.holds(joint);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
import type {
|
||||
ImpulseJoint,
|
||||
JointData,
|
||||
RevoluteImpulseJoint,
|
||||
RigidBody,
|
||||
World as RapierWorld,
|
||||
} from '@dimforge/rapier2d-compat';
|
||||
import { isHandleEnabled, worldMatrixOf } from '../../core/graph';
|
||||
import { isEntity } from '../../core/graph/values';
|
||||
import { hasConnectedAnchor, JOINT_CONNECTED_KEY } from '../../core/model/joint';
|
||||
import { referencedId } from '../../core/model/objectRefs';
|
||||
import type { PropertyValue, Vec2 } from '../../core/model/Properties';
|
||||
import { hingeLimits, jointFarEnd, jointLength, jointSettings } from '../../core/properties/joint';
|
||||
import type { Entity } from '../Entity';
|
||||
import type { World } from '../World';
|
||||
import { angleBetween, matrixPose, type Pose, round, samePose } from './bodyGeometry';
|
||||
import { type Rapier, toMetres } from './engine';
|
||||
|
||||
/** The body the engine moves for an object, and that object. */
|
||||
export interface RigidOwner {
|
||||
entity: Entity;
|
||||
body: RigidBody;
|
||||
}
|
||||
|
||||
/** What the joints need of the system that owns the bodies. */
|
||||
export interface JointHost {
|
||||
/** The nearest object from `from` upwards that has a rigidbody switched on; null when none has. */
|
||||
rigidAbove(from: Entity | null): RigidOwner | null;
|
||||
hint(world: World, target: Entity, text: string): void;
|
||||
}
|
||||
|
||||
/** One joint entity as the engine has it. `joint` is null while it holds nothing. */
|
||||
interface Held {
|
||||
joint: ImpulseJoint | null;
|
||||
/** What the engine joint was built from; it is built again when that changes. */
|
||||
key: string;
|
||||
/** A body of the joint's own standing for an end that has no rigidbody: it goes where that end is. */
|
||||
anchor: RigidBody | null;
|
||||
anchorPose: Pose | null;
|
||||
/** The length and the angle the two ends were placed at, kept while the same two bodies are held. */
|
||||
placed: { between: string; length: number; angle: number } | null;
|
||||
collide: boolean;
|
||||
}
|
||||
|
||||
const NO_RIGIDBODY = 'sits on an object without a rigidbody, so it holds nothing.';
|
||||
const GONE = 'lost its connected object, so it holds nothing.';
|
||||
const SAME_BODY = 'is connected to the object it sits on, so it holds nothing.';
|
||||
|
||||
/** The object a joint names: none (a point of the scene), one that is there, or one that is gone. */
|
||||
function connectedOf(world: World, joint: Entity): Entity | null | 'gone' {
|
||||
const value = joint.props[JOINT_CONNECTED_KEY] as PropertyValue | Entity | undefined;
|
||||
// A graph wrote the object itself (`Properties`); the scene's reference names it by id (#258).
|
||||
if (isEntity(value)) return world.entities.includes(value) ? value : 'gone';
|
||||
const ref = referencedId(value);
|
||||
if (!ref) return null;
|
||||
return world.findReferenced(joint, ref) ?? 'gone';
|
||||
}
|
||||
|
||||
/** A world point as a body at `pose` has it, in the engine's metres. */
|
||||
function inBody(pose: Pose, point: Vec2): Vec2 {
|
||||
const dx = point.x - pose.x;
|
||||
const dy = point.y - pose.y;
|
||||
const cos = Math.cos(pose.angle);
|
||||
const sin = Math.sin(pose.angle);
|
||||
return { x: toMetres(dx * cos + dy * sin), y: toMetres(-dx * sin + dy * cos) };
|
||||
}
|
||||
|
||||
const ORIGIN: Pose = { x: 0, y: 0, angle: 0 };
|
||||
|
||||
/**
|
||||
* The joints of the played game (#154): one engine joint per joint entity whose object has a
|
||||
* rigidbody. The other end is the connected object's body, or – where that has none, or nothing is
|
||||
* connected – a body of the joint's own that goes wherever that end is and is pulled by nothing.
|
||||
*/
|
||||
export class JointSet {
|
||||
private readonly held = new Map<Entity, Held>();
|
||||
|
||||
constructor(private readonly rapier: Rapier) {}
|
||||
|
||||
/** Makes the engine's joints match the joint entities; call once the bodies are in place. */
|
||||
sync(world: World, engine: RapierWorld, host: JointHost): void {
|
||||
const seen = new Set<Entity>();
|
||||
for (const entity of world.entities) {
|
||||
if (entity.type !== 'joint') continue;
|
||||
seen.add(entity);
|
||||
this.syncOne(world, engine, host, entity);
|
||||
}
|
||||
for (const [entity, held] of this.held) {
|
||||
if (seen.has(entity)) continue;
|
||||
this.release(engine, held);
|
||||
this.dropAnchor(engine, held);
|
||||
this.held.delete(entity);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the engine holds a joint for this entity right now. */
|
||||
holds(entity: Entity): boolean {
|
||||
return Boolean(this.held.get(entity)?.joint?.isValid());
|
||||
}
|
||||
|
||||
/** The engine is freed as a whole; what was held in it is only forgotten. */
|
||||
clear(): void {
|
||||
this.held.clear();
|
||||
}
|
||||
|
||||
private syncOne(world: World, engine: RapierWorld, host: JointHost, entity: Entity): void {
|
||||
let held = this.held.get(entity);
|
||||
if (!held) {
|
||||
held = {
|
||||
joint: null,
|
||||
key: '',
|
||||
anchor: null,
|
||||
anchorPose: null,
|
||||
placed: null,
|
||||
collide: false,
|
||||
};
|
||||
this.held.set(entity, held);
|
||||
}
|
||||
const idle = (why?: string) => {
|
||||
this.release(engine, held);
|
||||
this.dropAnchor(engine, held);
|
||||
if (why) host.hint(world, entity, why);
|
||||
};
|
||||
if (!isHandleEnabled(entity)) return idle();
|
||||
const own = host.rigidAbove(entity.parent);
|
||||
if (!own) return idle(NO_RIGIDBODY);
|
||||
const connected = connectedOf(world, entity);
|
||||
if (connected === 'gone') return idle(GONE);
|
||||
const rigid = connected ? host.rigidAbove(connected) : null;
|
||||
if (rigid?.body === own.body) return idle(SAME_BODY);
|
||||
if (!own.body.isEnabled() || (rigid && !rigid.body.isEnabled())) return idle();
|
||||
|
||||
const settings = jointSettings(entity.props);
|
||||
const ownPose = matrixPose(worldMatrixOf(own.entity));
|
||||
const otherPose = rigid
|
||||
? matrixPose(worldMatrixOf(rigid.entity))
|
||||
: connected
|
||||
? matrixPose(worldMatrixOf(connected))
|
||||
: ORIGIN;
|
||||
const other = rigid ? rigid.body : this.anchorAt(engine, held, otherPose);
|
||||
if (rigid) this.dropAnchor(engine, held);
|
||||
|
||||
const m = worldMatrixOf(entity);
|
||||
const at = { x: m.tx, y: m.ty };
|
||||
const far = jointFarEnd(settings, at, connected ? worldMatrixOf(connected) : null);
|
||||
const onOwn = inBody(ownPose, at);
|
||||
const twoEnds = hasConnectedAnchor(settings.type);
|
||||
// A hinge's and a fixed joint's point on the other body is wherever the joint was when it was
|
||||
// made, so it is no part of the key – the bodies move, and the point with them.
|
||||
const key = JSON.stringify([
|
||||
settings.type,
|
||||
own.body.handle,
|
||||
other.handle,
|
||||
[round(onOwn.x), round(onOwn.y)],
|
||||
twoEnds ? [round(inBody(otherPose, far).x), round(inBody(otherPose, far).y)] : 0,
|
||||
settings.length,
|
||||
settings.stiffness,
|
||||
settings.damping,
|
||||
settings.limits,
|
||||
]);
|
||||
if (!held.joint || key !== held.key) {
|
||||
this.release(engine, held);
|
||||
const between = `${settings.type}|${own.body.handle}|${other.handle}`;
|
||||
if (held.placed?.between !== between)
|
||||
held.placed = {
|
||||
between,
|
||||
length: Math.hypot(far.x - at.x, far.y - at.y),
|
||||
angle: angleBetween(other.rotation(), own.body.rotation()),
|
||||
};
|
||||
const data = this.dataOf(settings, held.placed, inBody(otherPose, far), onOwn, other, own.body);
|
||||
// The other end first: a hinge's angle is then the held object's turn against it.
|
||||
held.joint = engine.createImpulseJoint(data, other, own.body, true);
|
||||
// Only a hinge has limits, and a hinge is the engine's revolute joint.
|
||||
if (settings.limits)
|
||||
(held.joint as RevoluteImpulseJoint).setLimits(...hingeLimits(settings.limits, held.placed.angle));
|
||||
held.joint.setContactsEnabled(settings.collideConnected);
|
||||
held.key = key;
|
||||
held.collide = settings.collideConnected;
|
||||
return;
|
||||
}
|
||||
if (held.collide !== settings.collideConnected) {
|
||||
held.collide = settings.collideConnected;
|
||||
held.joint.setContactsEnabled(held.collide);
|
||||
own.body.wakeUp();
|
||||
}
|
||||
}
|
||||
|
||||
private dataOf(
|
||||
settings: ReturnType<typeof jointSettings>,
|
||||
placed: NonNullable<Held['placed']>,
|
||||
onOther: Vec2,
|
||||
onOwn: Vec2,
|
||||
other: RigidBody,
|
||||
own: RigidBody,
|
||||
): JointData {
|
||||
const { JointData } = this.rapier;
|
||||
switch (settings.type) {
|
||||
case 'hinge':
|
||||
return JointData.revolute(onOther, onOwn);
|
||||
case 'spring':
|
||||
return JointData.spring(
|
||||
toMetres(jointLength(settings, placed.length)),
|
||||
settings.stiffness,
|
||||
settings.damping,
|
||||
onOther,
|
||||
onOwn,
|
||||
);
|
||||
case 'rope':
|
||||
return JointData.rope(toMetres(jointLength(settings, placed.length)), onOther, onOwn);
|
||||
case 'fixed':
|
||||
// The frames differ by how the two are turned against each other right now, which is kept.
|
||||
return JointData.fixed(onOther, 0, onOwn, other.rotation() - own.rotation());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The joint's own body for an end without a rigidbody, put where that end is. It is moved the way
|
||||
* a kinematic body is, so what hangs on it is dragged along rather than snapped.
|
||||
*/
|
||||
private anchorAt(engine: RapierWorld, held: Held, pose: Pose): RigidBody {
|
||||
const t = { x: toMetres(pose.x), y: toMetres(pose.y) };
|
||||
if (!held.anchor) {
|
||||
const desc = this.rapier.RigidBodyDesc.kinematicPositionBased();
|
||||
held.anchor = engine.createRigidBody(desc.setTranslation(t.x, t.y).setRotation(pose.angle));
|
||||
held.anchorPose = pose;
|
||||
return held.anchor;
|
||||
}
|
||||
if (!held.anchorPose || !samePose(pose, held.anchorPose)) {
|
||||
held.anchor.setNextKinematicTranslation(t);
|
||||
held.anchor.setNextKinematicRotation(pose.angle);
|
||||
held.anchorPose = pose;
|
||||
}
|
||||
return held.anchor;
|
||||
}
|
||||
|
||||
private release(engine: RapierWorld, held: Held): void {
|
||||
// A body that left the engine took its joints along: such a joint is only forgotten.
|
||||
if (held.joint?.isValid()) engine.removeImpulseJoint(held.joint, true);
|
||||
held.joint = null;
|
||||
held.key = '';
|
||||
}
|
||||
|
||||
private dropAnchor(engine: RapierWorld, held: Held): void {
|
||||
if (!held.anchor) return;
|
||||
// Its joint goes with it, so that is let go of first.
|
||||
this.release(engine, held);
|
||||
engine.removeRigidBody(held.anchor);
|
||||
held.anchor = null;
|
||||
held.anchorPose = null;
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,9 @@ import type { EntityHandle, NodeContext, PhysicsControl, SharedState } from '../
|
||||
import { keyName } from '../../core/keys';
|
||||
import { collisionFilterOf } from '../../core/model/collisionLayers';
|
||||
import type { Vec2 } from '../../core/model/Properties';
|
||||
import { findAssetOf, findScene, type Project } from '../../core/model/Project';
|
||||
import { JOINT_CONNECTED_KEY } from '../../core/model/joint';
|
||||
import { objectReference } from '../../core/model/objectRefs';
|
||||
import { findAsset, findAssetOf, findScene, type Project } from '../../core/model/Project';
|
||||
import { soundFileOf } from '../../core/model/sound';
|
||||
import { resolveAssetProps } from '../../core/properties/resolve';
|
||||
import { loopsOf, volumeOf } from '../../core/properties/sounds';
|
||||
@@ -153,6 +155,15 @@ export function behaviorContext(
|
||||
if (assetId === '' || file) run.audio.stop(file);
|
||||
},
|
||||
spawn: (assetId, position, parent) => world.spawn(assetId, position, resolve(parent) ?? null),
|
||||
addJoint: (assetId, owner, connected, at) => {
|
||||
const on = resolve(owner);
|
||||
if (!on || findAsset(project, assetId)?.type !== 'joint') return null;
|
||||
const joint = world.spawn(assetId, { ...at, z: 0 }, on);
|
||||
const to = resolve(connected);
|
||||
// By id, as a pick in the inspector stores it: the scene view of the run then draws the link too.
|
||||
if (joint && to) joint.props[JOINT_CONNECTED_KEY] = objectReference(to.objectId);
|
||||
return joint;
|
||||
},
|
||||
destroy: (target, keepChildren) => {
|
||||
const found = resolve(target);
|
||||
if (!found) return [];
|
||||
|
||||
Reference in new issue
Block a user