Skip to content
Plugins

Physics from a Plugin

Add bodies and joints to a session's physics world, push and steer them, change gravity, and reach bodies from a weapon the way the physics gun does.


Every session has one physics world, Jolt stepped by the host once a tick after the players move. The map’s own colliders are already in it, and so is every prop, ragdoll and physical projectile the session makes. A Plugin reaches it through its context’s Physics, a view of IPhysicsWorld of its own.

public void Load(PluginContext context)
{
    if (context.Realm != Realm.Server || context.Physics is not { } physics)
        return;
}

It’s null in a realm or session with no physics, so check it. A Plugin never steps the world; it adds to it and changes what’s in it, and the next step moves everything.

Every vector is a MapVector in metres on Godot’s axes, Y up. Velocity is metres a second, spin radians a second about each axis, mass kilograms, a push newton-seconds and a force newtons. Turns are Orientations, quaternions with helpers like Orientation.Yaw(45) and Orientation.Axis(axis, radians).

Adding a body

A body is made from a BodySpec over a CollisionContent, the same converted collision a prop’s model carries. The context doesn’t hand a Plugin a model’s collision yet, so build the shapes yourself from Colliders:

using System.Numerics;
using EvilEngine.Api.Physics;
using EvilEngine.Formats.Collision;
using EvilEngine.Formats.Maps;

var crate = new CollisionContent([
    new Collider(new ColliderShape.Box(new Vector3(0.8f, 0.8f, 0.8f)), [SolidContents.Solid])
]);

var body = physics.Add(new BodySpec(crate)
{
    Position = new MapVector(0, 2, 0),
    Orientation = Orientation.Yaw(45),
    Velocity = new MapVector(0, 0, -4),
    Mass = 30
});

A collider’s shape is a Box by its full size, a Sphere, Capsule or Cylinder by radius and height, a convex Hull of points, or a triangle Mesh. Each sits at its own Position and Rotation in the body’s space, so several colliders make one body of any shape.

What the spec leaves out has a default:

Key Default
Motion Dynamic. Static never moves, Kinematic moves only where you put it.
Position, Orientation The origin, unturned.
Mass The collision’s own mass, or its volume times its surface’s density, 1,000 kg/m³ when the surface has none.
Surface The collision’s own surface record. Its friction and bounce go on the body.
Velocity, Spin At rest. Only a dynamic body takes them.
Damping, SpinDamping The world’s own.

A dynamic body can’t be a triangle mesh, since Jolt can’t simulate one: make a mesh body static or kinematic.

A body added this way is simulated and traced against, but not drawn. It falls, collides with the world, props and other bodies, and weapons’ traces, bullets and the physics gun all hit it, but players see nothing there. There’s no Plugin call for a drawn prop yet; the spawn command makes one from a model.

Moving bodies

IPhysicsBody reads as the world stood after the last step, and you can change most of it:

body.Push(new MapVector(0, 300, 0), body.Centre);
body.Velocity = new MapVector(0, 0, -6);
body.Spin = new MapVector(0, Math.PI, 0);
body.GravityScale = 0;
body.Frozen = true;
body.Wake();
  • Push gives an impulse at a point in the world, all at once. At the body’s centre it moves without turning; anywhere else it turns as well.
  • Force lasts for the next step only, so a force that lasts is one you give every tick. A weapon’s Think runs every tick, so it can; a brain thinks less often and should push or set velocity instead.
  • Setting Position or Orientation moves the body there at once, with no sweep in between.
  • Frozen holds a dynamic body where it is, untouched by gravity and pushes, until you clear it.
  • GravityScale is how much of the world’s gravity pulls it, 1 by default.
  • A body at rest goes to sleep. Setting its velocity alone may not wake it, so call Wake.

Centre is its centre of mass, which isn’t its Position, the origin its collision was made around. Bounds is the box it covers now.

Gravity

Gravity starts as the map’s own, straight down: 15.24 m/s² on every Source map, 9.81 when a map doesn’t say. Setting it changes it for every body at once:

physics.Gravity = new MapVector(0, -1.6, 0);

It’s the bodies’ gravity. Players and NPCs move by their movement rules, which keep their own. Nothing puts it back when your Plugin unloads.

Joints

A joint holds a pivot on two bodies together and lets the child turn against the parent about the joint’s X, Y and Z axes, each within its limits. Make one from a JointSpec:

var hinge = physics.Join(new JointSpec(frame, door)
{
    Position = new MapVector(1, 1, 0),
    Limits = [new JointLimit(0, 0), new JointLimit(-1.5, 1.5), new JointLimit(0, 0)],
    Friction = [0, 20, 0]
});
  • Limits are three JointLimits of a min and a max in radians. JointLimit.Free leaves an axis free, and a limit whose min and max are the same locks it, so the door above swings about Y alone. The child never slides, only turns.
  • Friction holds each axis against turning up to that much torque.
  • Collide is false unless set, so the joined pair pass through each other. Every other body still collides with both.
  • Position and Orientation place the joint in the world as the bodies stand now. To place it in each body’s own space instead, set both InParent and InChild, as a ragdoll does from its model’s bind pose.

You can join any two of the world’s bodies, a prop someone spawned included. The joint is yours either way.

What’s yours

Bodies lists every body in the world, whoever added it, and you can push, freeze and join any of them. Remove takes out only the bodies and joints your Plugin added, and returns false for any other. Removing a body removes every joint on it too, and a body or joint that’s gone reads Removed, so a behaviour that keeps one between ticks checks it before touching it again.

When your Plugin unloads, every body and joint it added that’s still in the world goes with it. So does everything added by a Load that then throws.

Numbers that aren’t finite

Nothing that isn’t a number reaches Jolt, so a direction divided by a length of 0 throws where you set it, not somewhere later in the step. A position, velocity, push, force or orientation that isn’t finite, or is past a float’s range, throws ArgumentOutOfRangeException, as does an orientation of all zeros, a mass or inertia of 0 or less, damping below 0 and joint friction below 0. A dynamic mesh body, a joint whose bodies aren’t this world’s or are one body, and limits or frictions that aren’t three each throw ArgumentException.

From a weapon

A Plugin’s code runs while it loads and when the engine calls it: a weapon’s behaviour, a projectile’s, a brain or a damage decider. To reach the world from one, hand it the view as you make it. The physics gun is a weapon behaviour like any other, in Libraries/Plugins/evil.source/PhysicsGun.cs, and everything it does to a prop goes through the same calls.

Trace runs a line, or a box with a size, through the world, its props and its people, and its WeaponTrace names the Body it hit, or null for the world or a person. The physics gun grabs with it:

var hit = holder.Trace(holder.Eye, Along(holder, MaxRange));
if (hit.Body is not { Motion: BodyMotion.Dynamic, Removed: false } body)
    return;
body.GravityScale = 0;
body.Wake();

and then sets the held body’s Velocity and Spin every tick to steer its Centre to a point along the aim, puts GravityScale back to 1 when it lets go, and freezes it with Frozen on attack2.

Beam shows the glowing beam. A WeaponBeam is on a point in the world, or on a point in a body’s own space so it follows the body as it moves and turns:

var inverse = body.Orientation.Normalised().Inverse();
var local = inverse.Rotate(new MapVector(hit.End.X - body.Position.X, hit.End.Y - body.Position.Y,
    hit.End.Z - body.Position.Z));
holder.Beam = WeaponBeam.On(body, local);

Set it every tick it should show; each tick starts with none. On a body that isn’t a prop, such as one of yours, the beam ends at where that point is each tick. Strike pushes the dynamic body a trace this tick just hit, or hurts the person, and a projectile that’s physical has a body of its own.

Here’s a whole Plugin, a hook that hangs whatever you hit from the point you hit it, swinging free, and lets everything go on attack2. It adds a small static body as each anchor and joins the prop to it:

id = "hooks"
name = "Hooks"
version = "1.0.0"
api = 1
code = "Code/hooks.dll"
[weapon."weapon/hook"]
title = "Hook"
slot = 0
using EvilEngine.Api;
using EvilEngine.Api.Physics;
using EvilEngine.Api.Weapons;
using EvilEngine.Formats;
using EvilEngine.Formats.Collision;
using EvilEngine.Formats.Maps;

namespace Hooks;

public sealed class HookPlugin : IPlugin
{
    public void Load(PluginContext context)
    {
        if (context.Realm != Realm.Server || context.Physics is not { } physics)
            return;
        context.Weapons.Register(ContentId.Parse("hooks:weapon/hook"), () => new Hook(physics));
    }

    public void Unload()
    {
    }
}

sealed class Hook(IPhysicsWorld physics) : IWeaponBehaviour
{
    const double Reach = 30;

    static readonly CollisionContent Anchor =
        new([new Collider(new ColliderShape.Sphere(0.02f), [SolidContents.Solid])]);

    readonly List<IPhysicsBody> anchors = [];

    public void Deploy(IWeaponHolder holder)
    {
    }

    public void Think(IWeaponHolder holder)
    {
        if (holder.Pressed.HasFlag(WeaponButtons.Attack))
        {
            var end = new MapVector(holder.Eye.X + holder.Aim.X * Reach, holder.Eye.Y + holder.Aim.Y * Reach,
                holder.Eye.Z + holder.Aim.Z * Reach);
            var hit = holder.Trace(holder.Eye, end);
            if (hit.Body is { Motion: BodyMotion.Dynamic, Removed: false } body)
            {
                var anchor = physics.Add(new BodySpec(Anchor) { Motion = BodyMotion.Static, Position = hit.End });
                physics.Join(new JointSpec(anchor, body) { Position = hit.End });
                body.Wake();
                anchors.Add(anchor);
            }
        }

        if (holder.Pressed.HasFlag(WeaponButtons.Attack2))
        {
            foreach (var anchor in anchors)
                physics.Remove(anchor);
            anchors.Clear();
        }
    }

    public void Holster(IWeaponHolder holder)
    {
    }
}

Spawn an oil drum, hook it, and knock it with the physics gun to see it swing:

spawn gmod:models/props_c17/oildrum001
give hooks:weapon/hook

Removing an anchor takes its joint with it. Anchors left when the session ends go as the Plugin unloads. Making weapons gives the hook a view model, sounds and a beam of its own.