Pickup is a capability: PickupData/Pickup run a timed grab through Zone's hold API and TryPickUp (group A, sim)

GrabEvent carries a FloatingBodyId; Zone gains TryHold/SetHeldProgress/Free and places a held item instead of
integrating it; Entity.TractorPower is derived from Pickup.Power and TractorCommand is the pilot's input
(ActionGameManager writes it undamped, the Time.deltaTime ramp is deleted). Binder and FieldTester change the
delegate type only. PickupTests and a save round-trip pin for the player's zone index.

Group A builds; no beam is on any generated ship until group B.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-13 05:00:22 +02:00
commit 5aa989abbf
14 changed files with 736 additions and 27 deletions

View file

@ -189,6 +189,7 @@ public interface IPowerConsumer
Union(45, typeof(MunitionSeekerData)),
Union(46, typeof(MunitionControlData)),
Union(47, typeof(MunitionFuelData)),
Union(48, typeof(PickupData)),
JsonObject(MemberSerialization.OptIn)]
public abstract class BehaviorData
{

View file

@ -0,0 +1,157 @@
using System;
using System.Linq;
using CultMath;
using MessagePack;
using Newtonsoft.Json;
using static CultMath.math;
using float2 = CultMath.float2;
// The tractor beam: the capability that lets a ship collect floating items. It spins its beam up in sim time toward
// the pilot's command, and once the beam is up claims the free item nearest its axis and runs one timed grab
// (extend, envelop, pull) that ends in Zone.TryPickUp, the one commit of a pickup. Its stats are flat
// (Min == Max), as the other behaviours that carry their own timings.
[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class PickupData : BehaviorData
{
// How far along the beam's axis an item can be claimed, and how far off the axis.
[Inspectable, JsonProperty("range"), Key(1), RuntimeInspectable]
public PerformanceStat Range = new PerformanceStat();
[Inspectable, JsonProperty("beamRadius"), Key(2), RuntimeInspectable]
public PerformanceStat BeamRadius = new PerformanceStat();
// The spin-up (0..1) needed to claim an item, and to keep a grab going.
[Inspectable, JsonProperty("grabPower"), Key(3), RuntimeInspectable]
public PerformanceStat GrabPower = new PerformanceStat();
// Seconds of each phase of a grab.
[Inspectable, JsonProperty("extendTime"), Key(4), RuntimeInspectable]
public PerformanceStat ExtendTime = new PerformanceStat();
[Inspectable, JsonProperty("envelopTime"), Key(5), RuntimeInspectable]
public PerformanceStat EnvelopTime = new PerformanceStat();
[Inspectable, JsonProperty("pullTime"), Key(6), RuntimeInspectable]
public PerformanceStat PullTime = new PerformanceStat();
// Spin-up and spin-down, in power per sim second.
[Inspectable, JsonProperty("spinRate"), Key(7), RuntimeInspectable]
public PerformanceStat SpinRate = new PerformanceStat();
public override Behavior CreateInstance(EquippedItem item)
{
return new Pickup(this, item);
}
}
// Owns this ship's beam power and its one grab. Power is written only here; Zone owns the held item's pose.
public class Pickup : Behavior, IAlwaysUpdatedBehavior
{
private readonly PickupData _data;
// Power and the grab clock are kept in double so a fixed tick count lands on the same side of a boundary
// whatever dt the zone steps by.
private double _power;
private bool _grabbing;
private FloatingBodyId _target;
private double _elapsed;
// How many of Envelop and Pull have been published so far (0, 1 or 2).
private int _published;
public Pickup(PickupData data, EquippedItem item) : base(data, item)
{
_data = data;
}
// The beam's spun-up state in [0, 1]: what the pilot's command has driven it to.
public float Power => (float) _power;
public void Update(float dt)
{
var active = Item.Active.Value;
var command = active ? Math.Clamp(Entity.TractorCommand, 0f, 1f) : 0f;
var step = (double) Evaluate(_data.SpinRate) * dt;
_power = Math.Clamp(_power + Math.Clamp(command - _power, -step, step), 0.0, 1.0);
var zone = Entity.Zone;
var grabPower = Evaluate(_data.GrabPower);
var extend = (double) Evaluate(_data.ExtendTime);
var envelop = (double) Evaluate(_data.EnvelopTime);
var pull = (double) Evaluate(_data.PullTime);
var range = Evaluate(_data.Range);
var origin = Entity.Position.xz;
if (!_grabbing)
{
if (!active || _power < grabPower) return;
var item = Select(zone, origin, range, Evaluate(_data.BeamRadius));
if (item == null || !zone.TryHold(Entity, item.Id)) return;
_grabbing = true;
_target = item.Id;
_elapsed = 0;
_published = 0;
Publish(GrabPhase.Started, item, 0);
Publish(GrabPhase.Extend, item, (float) extend);
return;
}
var held = zone.FloatingItems.FirstOrDefault(f => f.Id.Equals(_target));
if (held == null || !ReferenceEquals(held.Holder, Entity))
{
_grabbing = false;
Entity.Capabilities.PublishGrab(new GrabEvent(_target, GrabPhase.Cancelled, float3(0), 0));
return;
}
var pulling = _elapsed >= extend + envelop;
if (!active || _power < grabPower || (!pulling && length(held.Body.Position - origin) > range))
{
_grabbing = false;
zone.Free(_target);
Publish(GrabPhase.Cancelled, held, 0);
return;
}
_elapsed += dt;
if (_published < 1 && _elapsed >= extend) { _published = 1; Publish(GrabPhase.Envelop, held, (float) envelop); }
if (_published < 2 && _elapsed >= extend + envelop) { _published = 2; Publish(GrabPhase.Pull, held, (float) pull); }
if (_published == 2)
zone.SetHeldProgress(_target, pull > 0 ? (float) ((_elapsed - extend - envelop) / pull) : 1f);
if (_elapsed < extend + envelop + pull) return;
_grabbing = false;
if (zone.TryPickUp(Entity, _target)) Publish(GrabPhase.Completed, held, 0);
else
{
zone.Free(_target);
Publish(GrabPhase.Cancelled, held, 0);
}
}
// The free item nearest the beam axis within Range along it and BeamRadius of it; ties go to the lowest id. A
// zero aim selects nothing.
private FloatingItem Select(Zone zone, float2 origin, float range, float radius)
{
var aim = Entity.Aim.xz;
if (lengthsq(aim) <= 0) return null;
var axis = normalize(aim);
FloatingItem best = null;
var bestOff = float.MaxValue;
foreach (var floating in zone.FloatingItems)
{
if (floating.Holder != null) continue;
var to = floating.Body.Position - origin;
var along = dot(to, axis);
var off = length(to - axis * along);
if (along < 0 || along > range || off > radius) continue;
if (off < bestOff || (off == bestOff && floating.Id.Value < best.Id.Value))
{
best = floating;
bestOff = off;
}
}
return best;
}
private void Publish(GrabPhase phase, FloatingItem item, float duration) =>
Entity.Capabilities.PublishGrab(new GrabEvent(item.Id, phase, float3(item.Body.Position.x, Entity.Position.y, item.Body.Position.y), duration));
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ac7678d240564331be7486588d28c5ee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -52,19 +52,18 @@ public enum GrabPhase
Cancelled
}
// The target is identified by a plain handle, not a Unity type: the simulation will own the real
// target identity (a loot drop or item instance id) once the pickup capability exists. Today's only
// publisher (the FieldShieldTest scene) hands out its own handles; nothing here interprets them.
// One phase of a grab. The target is the floating item the Pickup behaviour holds (the FieldShieldTest scene
// publishes its own handles as ids); nothing here interprets it.
public readonly struct GrabEvent
{
public readonly int TargetHandle;
public readonly FloatingBodyId Target;
public readonly GrabPhase Phase;
public readonly float3 TargetPosition;
public readonly float PhaseDuration;
public GrabEvent(int targetHandle, GrabPhase phase, float3 targetPosition, float phaseDuration)
public GrabEvent(FloatingBodyId target, GrabPhase phase, float3 targetPosition, float phaseDuration)
{
TargetHandle = targetHandle;
Target = target;
Phase = phase;
TargetPosition = targetPosition;
PhaseDuration = phaseDuration;

View file

@ -144,7 +144,11 @@ public abstract class Entity
public bool OverrideShutdown { get; set; }
public float TractorPower { get; set; }
// The pilot's tractor command (0..1); the Pickup behaviour spins its beam toward it.
public float TractorCommand;
// The beam's spun-up state: Pickup's, or 0 without one.
public float TractorPower => GetBehavior<Pickup>()?.Power ?? 0f;
public bool Active
{

View file

@ -42,7 +42,8 @@ public struct KinematicBody
}
// An item adrift in a zone: a death drop or jettisoned cargo. Zone.Release is its only adder; Zone's floating-item
// step (expiry) and TryPickUp are its only removers. Runtime state, never saved.
// step (expiry) and TryPickUp are its only removers. Zone.TryHold and Free are the only writers of Holder, the
// entity grabbing it with a tractor beam; a held item is placed by Zone, not drifted. Runtime state, never saved.
public sealed class FloatingItem
{
public FloatingBodyId Id;
@ -50,4 +51,9 @@ public sealed class FloatingItem
public KinematicBody Body;
public double ReleasedAt;
public float Lifetime;
// The entity holding it, or null when it floats free; HeldFrom is where it was claimed and HeldProgress how far
// along its pull to the holder (0..1).
public Entity Holder;
public float2 HeldFrom;
public float HeldProgress;
}

View file

@ -48,7 +48,8 @@ public class Zone
public ReactiveCollection<VapourCloud> Clouds = new ReactiveCollection<VapourCloud>();
// Floating items (death drops, jettisoned cargo), in release order. Zone owns their existence: Release is the one
// adder; StepFloatingItems (expiry) and TryPickUp are the only removers. Runtime state, never saved.
// adder; StepFloatingItems (expiry) and TryPickUp are the only removers. TryHold, Free and Remove-of-the-holder
// are the only writers of FloatingItem.Holder. Runtime state, never saved.
public ReactiveCollection<FloatingItem> FloatingItems = new ReactiveCollection<FloatingItem>();
public Dictionary<CultRecordKey, BodyData> Planets = new Dictionary<CultRecordKey, BodyData>();
public Dictionary<CultRecordKey, Planet> PlanetInstances = new Dictionary<CultRecordKey, Planet>();
@ -228,6 +229,8 @@ public class Zone
if (!_entities.Remove(entity)) return false;
_deathWatches.Remove(entity, out var watch);
watch.Dispose();
foreach (var floating in FloatingItems)
if (ReferenceEquals(floating.Holder, entity)) Free(floating.Id);
return true;
}
@ -330,14 +333,44 @@ public class Zone
// The one commit of a pickup: the first of the taker's cargo bays that accepts the item stores it and the item
// stops floating. Otherwise nothing changes.
// An item held by another entity is refused: one holder per item holds at the commit as well.
public bool TryPickUp(Entity taker, FloatingBodyId id)
{
var floating = FloatingItems.FirstOrDefault(f => f.Id.Equals(id));
if (floating == null || !taker.CargoBays.Any(bay => bay.TryStore(floating.Item))) return false;
if (floating == null || (floating.Holder != null && !ReferenceEquals(floating.Holder, taker))) return false;
if (!taker.CargoBays.Any(bay => bay.TryStore(floating.Item))) return false;
FloatingItems.Remove(floating);
return true;
}
// The tractor beam's claim on a floating item: false if it is absent or already held. The item stays where it is
// until its pull begins; StepFloatingItems places it from then on.
public bool TryHold(Entity holder, FloatingBodyId id)
{
var floating = FloatingItems.FirstOrDefault(f => f.Id.Equals(id));
if (floating == null || floating.Holder != null) return false;
floating.Holder = holder;
floating.HeldFrom = floating.Body.Position;
floating.HeldProgress = 0;
return true;
}
// How far along its pull to the holder a held item is, 0..1.
public void SetHeldProgress(FloatingBodyId id, float progress)
{
var floating = FloatingItems.FirstOrDefault(f => f.Id.Equals(id));
if (floating?.Holder != null) floating.HeldProgress = saturate(progress);
}
// Lets a held item go: it floats on from where it is with the Velocity and Drift it had.
public void Free(FloatingBodyId id)
{
var floating = FloatingItems.FirstOrDefault(f => f.Id.Equals(id));
if (floating == null) return;
floating.Holder = null;
floating.HeldProgress = 0;
}
// Called from the death subscription, before the entity leaves the zone: one generator per death. Each equipped
// item but the hull drops on a LootDropProbability draw; every cargo stack drops whole. Each drop leaves from the
// dead entity's position at a random heading. Draw order: Equipment order (the probability draw, then the heading
@ -359,12 +392,18 @@ public class Zone
}
// After StepClouds and before FireControl.Step: each floating item drifts as a KinematicBody on the zone's force
// and is removed once its lifetime has run out.
// and is removed once its lifetime has run out. A held item is neither integrated nor expired: it is placed
// between where it was claimed and its holder, now that the entities have moved.
private void StepFloatingItems(float deltaTime)
{
var settings = _itemManager.GameplaySettings;
foreach (var floating in FloatingItems.ToArray())
{
if (floating.Holder != null)
{
floating.Body.Position = lerp(floating.HeldFrom, floating.Holder.Position.xz, smoothstep(0f, 1f, floating.HeldProgress));
continue;
}
floating.Body.Step(deltaTime, GetForce(floating.Body.Position), settings);
if (floating.ReleasedAt + floating.Lifetime <= _time) FloatingItems.Remove(floating);
}